FactoryGirl attributes_for和association

时间:2012-10-24 00:33:51

标签: ruby-on-rails-3 factory-bot

我正在尝试在Rspec控制器测试中测试关联。问题是Factory不会为attributes_for命令生成关联。所以,按照this post中的建议,我在我的控制器规范中定义了我的验证属性,如下所示:

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和expert设置为true:

  {:id=>nil, :user_id=>2, :country_id=>1, :client=>true, :expert=>false, :created_at=>nil, :updated_at=>nil}

1 个答案:

答案 0 :(得分:4)

您的puts方法中的最后一行似乎有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和{{1}中添加行,就可以在工厂中执行此操作} country工厂。当您运行entitlement时,它会自动创建它们(但实际上不会保存FactoryGirl.build(:entitlement)记录)。