Back

Rails mintiest test associations

added on :: 21 November 2014
Say you have users and a user has many orders

In you test/models/user.rb
  test "user orders association" do
      assert_equal 2,  @user.orders.count
      assert @user.respond_to? "orders"
   end

in your fixtures

test/fixtures/users.yml

useone:
  email: hello@example.com
  encrypted_password: <%= BCrypt::Password.create('Hello1234') %>
  custom_key: '<%=User.random_key_for_user%>'
  first_name: Mike
  last_name: Day
  phone: 12346568769

test/fixtures/orders.yml

orderone:
  email: hello@today.com
  user: userone
  first_name: Sara
  last_name: Jone


ordertwo:
  email: hello@tomorrow.com
  user: userone
  first_name: Blake
  last_name: Seven


You define the association in the fixture by defining user with the user reference. In this instance it is 'userone' 

 if you are not using fixtures or factories to generate objects you could do something like bellow

user = User.create(email: "hello@example.com", encrypted_password:  BCrypt::Password.create('Hello1234'), first_name: "Mike" , last_name => "Day )
2.times { user.orders.create( first_name: "Sara", email: "sara@example.com" ) }

assert_equal 2, user.orders.count 

 happy testing



Back