Reputation: 3032
I have a model that has an association like this:
belongs_to :state_user, class_name: "User", foreign_key: "state_user_id"
In the fixtures I have this:
Model in question:
one:
state_user: administrator (User)
Users:
administrator:
name_first: 'Joe'
name_last: 'Administrator'
yet in my tests this association fails like this:
test 'should have state user' do
assert @transfer.state_user.present?
end
FAIL TransfersControllerTest#test_should_have_state_user (174.10s)
Expected false to be truthy.
test/controllers/transfers_controller_test.rb:64:in `block in <class:TransfersControllerTest>'
I have run into this before and my hack has been to do this and directly reference by the user id:
one:
state_user_id: 99
# state_user: administrator (User)
fixed:
id: 99
name_first: "Mary"
name_last: "Fixed"
This test then passes but not ideal. This code works fine in development and production - just fails in this particular case. My only thought is I am missing something with the belongs_to
declaration.
UPDATE
Added a bugbye break as suggested in the comments:
(byebug) @transfer.state_user
nil
(byebug) @transfer.state_user_id
924281465
(byebug) User.where(name_first: 'Joe')
#<User id: 417269330, name_first: "Joe", name_last: "Administrator">
I have run this again trying different users - same results. It's almost like the user ids are being created a second time after they are set in the Transfer models etc.
On a side note I have other belongs_to
users like this:
belongs_to :state_user, class_name: "User", foreign_key: "state_user_id"
# The user that created the transfer
belongs_to :initiated_user, class_name: "User", foreign_key: "initiated_user_id"
# The user that the transfer is assigned to
belongs_to :user
# The user that approves the transfer to proceed
belongs_to :approval_user, class_name: "User", foreign_key: "approval_user_id"
# The user that completed the transfer
belongs_to :completed_user, class_name: :user, foreign_key: "complete_user_id"
and now only the last one throws this error:
Minitest::UnexpectedError: ActiveRecord::Fixture::FixtureError: table "transfers" has no columns named "complete_user".
All of these belongs_to
Users also return the wrong user accossiation.
Upvotes: 1
Views: 623
Reputation: 3032
What a crazy issue 🤦♂️
I stumbled across this old post:
https://brandonhilkert.com/blog/7-reasons-why-im-sticking-with-minitest-and-fixtures-in-rails/
From that I realized that I didn't need to specify (User)
in my fixtures as they are not polymorphic. Removing that fixed the issue
one:
state_user: administrator
Also a 🤦♂️ moment for the complete_user
- needs to be:
one:
state_user: administrator
completed_user: operator # NOT complete_user
Hope this helps someone else down the road.
Upvotes: 1