Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I stub a method globally using RSpec?

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.

like image 688
p.matsinopoulos Avatar asked Nov 26 '13 13:11

p.matsinopoulos


People also ask

What is stubbing in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet. Here is the code from the section on RSpec Doubles − class ClassRoom def initialize(students) @students = students End def list_student_names @students.

How do I mock an instance variable in RSpec?

You can't mock an instance variable. You can only mock methods. One option is to define a method inside OneClass that wraps the another_member , and mock that method. However, you don't have to, there is a better way to write and test your code.

What is Allow_any_instance_of?

Use allow_any_instance_of(Class).to receive when you want to configure how. instances of the given class respond to a message without setting an. expectation that the message will be received.

What is a partial double RSpec?

A partial test double is an extension of a real object in a system that is instrumented with. test-double like behaviour in the context of a test. This technique is very common in Ruby. because we often see class objects acting as global namespaces for methods.


1 Answers

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

like image 93
Ioannis Karadimas Avatar answered Oct 04 '22 20:10

Ioannis Karadimas