I'm trying to test associations in my Rspec controller tests. Problem is that Factory doesn't produce associations for the attributes_for command. So, following the suggestion in this post I defined my validate attributes in my controller spec like so:
def valid_attributes
user = FactoryGirl.create(:user)
country = FactoryGirl.create(:country)
valid_attributes = FactoryGirl.build(:entitlement, user_id: user.id, country_id: country.id, client: true).attributes.symbolize_keys
puts valid_attributes
end
However, when the controller test runs I still get the following errors:
EntitlementsController PUT update with valid params assigns the requested entitlement as @entitlement
Failure/Error: entitlement = Entitlement.create! valid_attributes
ActiveRecord::RecordInvalid:
Validation failed: User can't be blank, Country can't be blank, Client & expert are both FALSE. Please specify either a client or expert relationship, not both
Yet the the valid_attributes output in the terminal clearly shows that each valid_attribute has a user_id, country_id and expert is set to true:
{:id=>nil, :user_id=>2, :country_id=>1, :client=>true, :expert=>false, :created_at=>nil, :updated_at=>nil}
It looks like you have a puts
as the last line in your valid_attributes
method, which returns nil. That's why when you pass it to Entitlement.create!
you get an error about user and country being blank, etc.
Try removing that puts
line, so you have just:
def valid_attributes
user = FactoryGirl.create(:user)
country = FactoryGirl.create(:country)
FactoryGirl.build(:entitlement, user_id: user.id, country_id: country.id, client: true).attributes.symbolize_keys
end
Incidentally, you shouldn't really be creating users and countries and then passing their ids to build
, you can do that in the factory itself just by including lines with user
and country
in the entitlement
factory. When you run FactoryGirl.build(:entitlement)
it will then automatically create them (but not actually save the entitlement
record).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With