我正在尝试在我的 Rspec 控制器测试中测试关联。问题是 Factory 不会为 attributes_for 命令生成关联。因此,按照这篇文章中的建议,我在控制器规范中定义了我的验证属性,如下所示:
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
但是,当控制器测试运行时,我仍然收到以下错误:
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
然而,终端中的 valid_attributes 输出清楚地表明每个 valid_attribute 都有一个 user_id、country_id 并且专家设置为 true:
{:id=>nil, :user_id=>2, :country_id=>1, :client=>true, :expert=>false, :created_at=>nil, :updated_at=>nil}