Search code examples
ruby-on-railstestingrspecruby-on-rails-5rspec-rails

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


I am using Rspec to test my rails application and FactoryBot (new nome for factory girl) to create mocks. But in each file I need to call a lot of mocks. And it's almost the something, call some mocks, create an user, login and confirm this user. Can I create a method to call all this mocks, login and confirm the user? Then I just need to call this method.

Here is what I call in each rspec file:

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

I'm thinking something like:

def call_mocks
  # put the code above
end

Than in each rspec file:

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

    call_mocks

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

  end
end

Solution

  • You should simply use shared context for that https://relishapp.com/rspec/rspec-core/v/3-4/docs/example-groups/shared-context

    It is similar to shared_example but for context which is what you want

    Nevertheless, you you got exactly the same setting for a lot of tests, consider putting them together in the same context

    Enjoy :)