2

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

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

我的问题是我怎么把它弄干?我查看了共享上下文,但后来我无法访问我的模型。我可以创建一个辅助方法并返回一个对象数组/散列,但似乎应该有一些内置的东西以一种优雅的方式来做到这一点。

4

2 回答 2

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

然后在你的规范中:

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

  # ...
end
于 2013-03-12T20:36:38.863 回答
0

一种选择是使用 FactoryGirl 的回调功能:

在您的测试中,您可能会执行类似的操作

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

您的工厂定义将类似于:

FactoryGirl.define do
  factory :a_model do

    factory :a_model_with_another do
      after(:create) {FactoryGirl.create(:another)}
    end
  end
end

您可以在文档中找到更多详细信息

于 2013-03-12T20:33:49.150 回答