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

Nie*_*tra 2 ruby rspec2 ruby-on-rails-3 factory-bot

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

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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*Sam 5

查看共享上下文:

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
Run Code Online (Sandbox Code Playgroud)

然后在您的规范中:

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

  # ...
end
Run Code Online (Sandbox Code Playgroud)