【问题标题】:FactoryGirl and belongs_to association when testing Rspec测试 Rspec 时的 FactoryGirl 和 belongs_to 关联
【发布时间】:2013-03-21 07:57:26
【问题描述】:

我有以下型号:

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") 值 (?, ?, ?, ?, ?)

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

谢谢

【问题讨论】:

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


【解决方案1】:

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

如果user_id 是必填字段并且您尝试使用FactoryGirl.create(attributes_for(:team)) 创建Team 的实例,则会引发错误。

但是,如果您使用FactoryGirl.create(:team),它应该会为您提供Team 的有效实例。

【讨论】:

    【解决方案2】:

    您不应该将 before(:each) 与 FactoryGirl 和 Rspec 一起使用,事实上,根据 The Rails 4 Way 第 21 章,创建此测试的更优雅的方法是在您的 it 语句之前使用 let(:team) { FactoryGirl.create(:team }

    这允许您不使用太多实例变量,如果需要,如果此解释不充分,我可以提供一个示例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多