加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 测试Rspec时的FactoryGirl和belongs_to协会

发布时间:2020-12-17 02:34:09 所属栏目:百科 来源:网络整理
导读:我有以下型号: class Team ActiveRecord::Base # Setup accessible (or protected) attributes for your model attr_accessible :name validates_presence_of :name belongs_to :userend 哪个经过测试: describe Team do before(:each) do @attr = Factory
我有以下型号:

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 should belong to a user
Failure/Error: @team = Team.create!(@attr)
ActiveRecord::StatementInvalid:
SQLite3::ConstraintException: teams.user_id may not be NULL: INSERT INTO “teams” (“created_at”,“name”,“sport_id”,“updated_at”,
“user_id”) VALUES (?,?,?)

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

谢谢

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读