5

我正在尝试在我的 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}
4

1 回答 1

4

看起来您的方法puts的最后一行是a valid_attributes,它返回 nil。这就是为什么当您将其传递给Entitlement.create!您时会收到有关用户和国家/地区为空白等错误的原因。

尝试删除该puts行,因此您只需:

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

顺便说一句,您不应该真正创建用户和国家,然后将他们的 id 传递给build,您可以在工厂本身中执行此操作,只需在工厂中添加user和。当您运行时,它会自动创建它们(但不会实际保存记录)。countryentitlementFactoryGirl.build(:entitlement)entitlement

于 2012-10-24T00:58:00.647 回答