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
putsas the last line in yourvalid_attributesmethod, which returns nil. That’s why when you pass it toEntitlement.create!you get an error about user and country being blank, etc.Try removing that
putsline, so you have just: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 withuserandcountryin theentitlementfactory. When you runFactoryGirl.build(:entitlement)it will then automatically create them (but not actually save theentitlementrecord).