【问题标题】:Sharing factories across rspec specs in a DRY way以 DRY 方式跨 rspec 规范共享工厂
【发布时间】:2013-03-12 20:20:47
【问题描述】:

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

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

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

【问题讨论】:

    标签: ruby ruby-on-rails-3 rspec2 factory-bot


    【解决方案1】:

    查看共享上下文:

    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
    

    【讨论】:

    • 我之前不知道 let 命令。这正是我所需要的。谢谢
    【解决方案2】:

    一种选择是使用 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
    

    您可以在docs找到更多详细信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 2014-04-17
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      相关资源
      最近更新 更多