gpt4 book ai didi

ruby-on-rails - 测试 Rspec 时 FactoryGirl 和belongs_to 关联

转载 作者:行者123 更新时间:2023-12-04 06:08:38 25 4
gpt4 key购买 nike

我有以下模型:

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 会抛出错误是必填字段,您正在尝试创建 Team 的实例通过使用 FactoryGirl.create(attributes_for(:team)) .

但是,如果您使用 FactoryGirl.create(:team)它应该给你一个有效的 Team 实例.

关于ruby-on-rails - 测试 Rspec 时 FactoryGirl 和belongs_to 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15723184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com