Rspec: 如何创建一个方法来调用和创建所有模拟?

Rspec: how to create a method to call and create all mocks?

我正在使用 Rspec 来测试我的 rails 应用程序和 FactoryBot(工厂女孩的新名字)来创建模拟。但是在每个文件中我都需要调用很多模拟。这几乎就是一些东西,调用一些模拟,创建一个用户,登录并确认这个用户。我可以创建一个方法来调用所有这些模拟、登录并确认用户吗?那我只需要调用这个方法就可以了。

这是我在每个 rspec 文件中调用的内容:

let!(:nivel_super) { create(:nivel_super) }
let!(:gestora_fox) { create(:gestora_fox) }
let!(:user_mock) { create(:simple_super) }
let!(:super_user) { create(:super_user, 
  nivel_acesso_id: nivel_super.id, gestora_id: gestora_fox.id) }

let!(:ponto_venda) { create(:ponto_venda1) }
let!(:tipo_op) { create(:tipo_op) }

before(:each) do
  @request.env["devise.mapping"] = Devise.mappings[:user]
  super_user.confirm
  sign_in super_user
end

我在想:

def call_mocks
  # put the code above
end

比在每个 rspec 文件中:

RSpec.describe OrdemPrincipalsController, type: :controller do
  describe 'Ordem Principal tests' do

    call_mocks

    it 'go to new page' do
      # my test
    end

  end
end

你应该简单地使用共享上下文 https://relishapp.com/rspec/rspec-core/v/3-4/docs/example-groups/shared-context

它与 shared_example 类似,但上下文是您想要的

尽管如此,很多测试的设置完全相同,请考虑将它们放在相同的上下文中

尽情享受吧:)