user
user

Reputation: 1381

Rspec use application controller method

I have method in my application controller and want to use it everywhere in my integration specs.

I don't want to add it method in every spec

Currently i use

 allow_any_instance_of(ApplicationController).to receive(:set_seo).and_return('seo_text')

but it is inconvenient.

What should i do for it?

Upvotes: 1

Views: 277

Answers (2)

Yorkshireman
Yorkshireman

Reputation: 2343

I would create a spec_helper_integration file and put functionality specific to integration specs in there.

You should already have require 'rails_helper' at the top of all your specs. At the top of your integration specs put:

require 'rails_helper'
require 'spec_helper_integration'

Then create a spec_helper_integration.rb file in the same folder as your rails_helper.rb file.

spec_helper_integration:

#I'm taking a guesstimate as to your integration spec configuration, but it's
#likely something like the following line:

#don't also have this in your spec_helper or rails_helper files:
require 'capybara/rails'

#configure your integration specs:
RSpec.configure do |config|
  config.before(:each) do
    allow_any_instance_of(ApplicationController).to receive(:set_seo).and_return('seo_text')
  end
end

It's good practice to isolate code to where it is required only; by doing this, your ApplicationController method stubbing is only activated during the running of your integration specs and not your other specs, such as unit or controller specs, for example.

Moving forward, any further integration-spec-specific code should only be put in your spec_helper_integration file, too.

Upvotes: 0

DickieBoy
DickieBoy

Reputation: 4956

In your Rspec config you can configure a before and after block for :

before suite

before all

before each

after each

after all

after suite

https://www.relishapp.com/rspec/rspec-core/v/2-2/docs/hooks/before-and-after-hooks

In that order.

I would suggest:

RSpec.configure do |config|
  config.before(:suite) do
     allow_any_instance_of(ApplicationController).to receive(:set_seo).and_return('seo_text')
  end
end

Edit:

It appears that before(:suite) can cause problems.

If it doesn't work for you use before(:each)

Upvotes: 1

Related Questions