FactoryGirl attributes_for和association

Bet*_*rds 5 ruby-on-rails-3 factory-bot

我正试图在我的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
Run Code Online (Sandbox Code Playgroud)

但是,当控制器测试运行时,我仍然会收到以下错误:

 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
Run Code Online (Sandbox Code Playgroud)

然而,终端中的valid_attributes输出清楚地显示每个valid_attribute都有user_id,country_id和expert设置为true:

  {:id=>nil, :user_id=>2, :country_id=>1, :client=>true, :expert=>false, :created_at=>nil, :updated_at=>nil}
Run Code Online (Sandbox Code Playgroud)

Chr*_*erg 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
Run Code Online (Sandbox Code Playgroud)

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