gpt4 book ai didi

ruby-on-rails - 使用 Factory_girl 建立测试中关联

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:11 27 4
gpt4 key购买 nike

我希望能够仅在每个特定测试中创建与 ID 的关联,尽量避免在工厂中定义它们。我一直在关注Rails 4 Test Prescriptions

Avoid defining associations automatically in factory_girl definitions.Set them test by test, as needed. You’ll wind up with more manageabletest data.

class Workspace < ActiveRecord::Base
has_many :projects
end
class Project < ActiveRecord::Base
belongs_to :workspace
end

这就是我想要的

test "" do
project_with_id = build_stubbed(:project)
workspace_with_id = build_stubbed(:workspace)
workspace_with_id.projects.push(project_with_id)
end

我正在使用 build_stubbed 创建有效 ID,这会出现以下错误:

*** RuntimeError Exception: stubbed models are not allowed to access the database - Project#save({:validate=>true})

于是,读厂妹的documentation我想出了工作协会,但我不想在工厂里定义它们,甚至没有特征。

FactoryGirl.define do
factory :project do
association :workspace, strategy: :build_stubbed
end
end

test "" do
project = build_stubbed(:project)
end

这是有效的,因为我可以调用 project.workspace,并且两者都有一个有效的 ID

如何创建有效的关联(带 ID),但不接触数据库,仅使用 Factory girl 创建独立对象?

最佳答案

如果你正在使用 Rspec,你可以做这样的事情

 let!(:user1) { FactoryGirl.create(:user) }
let!(:user_social_profile1) { FactoryGirl.create(:user_social_profile, user_id: user1.id) }

也在 Rspec

let!(:user1) { FactoryGirl.create(:user) }
let!(:user_social_profile1) { FactoryGirl.create(:user_social_profile, user: user1) }

我相信在 minitest/test_unit 中

user1 = FactoryGirl.create(:user)
user_social_profile1 = FactoryGirl.create(:user_social_profile, user_id: user1.id)

很抱歉,我没有解释与工厂协会一起使用 build_stubbed 的相关问题,this答案很好地解释了这一点。

关于ruby-on-rails - 使用 Factory_girl 建立测试中关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40228976/

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