I have 2 models :
class User < ApplicationRecord
has_many :games, dependent: :nullify
class Game < ApplicationRecord
belongs_to :user
belongs_to :playlist, optional: true
In my fixtures, game only belongs_to users. My only fixtures are :
user.yml
michel:
id: 1
pseudo: michelchardou
email: mich@chardou.com
encrypted_password: User.digest('password')
admin: false
game.yml
game1:
user: michel
token: 123456
total_score: 0
My basic tests work for
test "should get expected game fixture token" do
assert_equal '123456', @game1.token
assert_equal 0, @game1.total_score
end
but the following raises an error :
test "should get expected game fixture user" do
assert_equal 'michel', @game1.user
end
the error is :
Failure:
GameTest#test_should_get_expected_game_fixture_user [/Users/pierre/code/pierregarciafr/wadzatsong/test/models/game_test.rb:25]:
Expected: "michel"
Actual: nil
Why ?
That's because you're manually assigning the id your user (michel) is going to have, and you should leave that to Rails (or the ORM), try deleting that line.
The fixture for the user michel should be like:
michel:
pseudo: michelchardou
email: mich@chardou.com
encrypted_password: User.digest('password')
admin: false
In the other hand your first example works without problem because you're not testing the relationship between both models, you're checking what was explicitly added to the fixture file.