gpt4 book ai didi

ruby - 以 DRY 方式跨 rspec 规范共享工厂

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:10 25 4
gpt4 key购买 nike

所以我有一些像这样的模型规范:

describe 'something' do
it 'another thing' do
a_model = FactoryGirl.create(:a_model)
another = FactoryGirl.create(:another)
#some code using a_model and another
end
end

然后,我有另一个模型规范:

describe 'something else' do
it 'another test' do
a_model = FactoryGirl.create(:a_model)
another = FactoryGirl.create(:another)
#different code using a_model and another
end
end

我的问题是如何将其干燥?我查看了共享上下文,但后来无法访问我的模型。我可以创建一个辅助方法并返回对象的数组/散列,但似乎应该内置一些东西以优雅的方式执行此操作。

最佳答案

检查共享上下文:

https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-context

# /spec/support/shared_stuff.rb

shared_context "shared stuff" do
let(:model_1) { FactoryGirl.create(:model_1) }
let(:model_2) { FactoryGirl.create(:model_2) }
end

然后在你的规范中:

describe "group that includes a shared context using 'include_context'" do
include_context "shared stuff"

# ...
end

关于ruby - 以 DRY 方式跨 rspec 规范共享工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15371339/

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