我正在尝试在Rspec Controller 测试中测试关联。问题是Factory不会为attribute_for命令生成关联。因此,按照this post中的建议,我在 Controller 规范中定义了我的validate属性,如下所示:

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

但是,当 Controller 测试运行时,我仍然收到以下错误:
 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}

最佳答案

好像您有一个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工厂中包含带有countryentitlement的行,就可以在工厂本身中做到这一点。当您运行FactoryGirl.build(:entitlement)时,它将自动创建它们(但实际上不保存entitlement记录)。

关于ruby-on-rails-3 - FactoryGirl attributes_for和关联,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13041362/

10-12 15:00