How should I stub a method globally using RSpec?

p.matsinopoulos picture p.matsinopoulos · Nov 26, 2013 · Viewed 20.4k times · Source

I am working on a Rails application. I am trying to stub a method globally.

What I am doing is to stub it inside the RSpec configuration, on a before(:suite) block as follows:

RSpec.configure do |config|
  config.before(:suite) do
    allow_any_instance_of(MyModel).to receive(:my_method).and_return(false)
  end
end

However, starting the test fails with the following error:

in `method_missing': undefined method `allow_any_instance_of' for #<RSpec::Core::ExampleGroup:0x00000008d6be08> (NoMethodError)

Any clue? How should I stub a method globally using RSpec?

P.

Answer

Ioannis Karadimas picture Ioannis Karadimas · Nov 26, 2013

It probably is a context / initialization issue. Doing it in config.before(:each) should solve your problem.