4

我有以下模型:

class Team < ActiveRecord::Base
  # Setup accessible (or protected) attributes for your model
  attr_accessible :name
  validates_presence_of :name

  belongs_to :user

end

由以下人员测试:

describe Team do

  before(:each) do
    @attr = FactoryGirl.attributes_for(:team)
  end

  it "should belong to a user" do
    @team = Team.create!(@attr)
    @team.should belong_to(:user)
  end
end

我有以下工厂:

FactoryGirl.define do
  factory :team do
    name 'Dream Team'
    sport
    user
  end
end

FactoryGirl.define do
  factory :user do
    name 'Test User'
    last_name 'Last Name'
    email 'example@example.com'
    password 'changeme'
    password_confirmation 'changeme'
  end
end

当我测试规范时,我得到以下失败:

1) 团队应该属于一个用户失败/错误:@team = Team.create!(@attr) ActiveRecord::StatementInvalid: SQLite3::ConstraintException: teams.user_id 不能为 NULL: INSERT INTO "teams" ("created_at" , "name", "sport_id", "updated_at", "user_id") 值 (?, ?, ?, ?, ?)

这是为什么?在文档中它说要设置关联,您只需编写工厂名称,在我的情况下是用户。

谢谢

4

2 回答 2

4

FactoryGirl.attributes_for将为您提供一个仅包含指定模型属性的哈希,不包括关联属性 - 在您的情况下,user_id.

That will throw up errors in case user_id is a required field and you're trying to create an instance of Team by using FactoryGirl.create(attributes_for(:team)).

However, if you use FactoryGirl.create(:team) it should give you a valid instance of Team.

于 2013-03-30T20:55:22.667 回答
0

You should not be using before(:each) with FactoryGirl and Rspec, in fact a more elegant way of creating this test, according to The Rails 4 Way Chapter 21, is by using let(:team) { FactoryGirl.create(:team } prior to your it statements

this allows you to not use so many instance variables, if desired I can provide an example if this explanation is not sufficient

于 2015-01-08T19:48:49.337 回答