Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a stub that applies to all spec files in RSpec

I'm wanting to know if there is an easy way to include a stub in all of my spec files. I'm using the Geocoder gem and when I run my RSpec tests I don't want it attempting to download the location information.

I've found the following solution which works perfectly. However, I don't want to write the same three lines in every spec file.

before(:each) do
  User.any_instance.stub(:geocode) { [1,1] }
end

Is it possible to put something in my spec_helper.rb file?

like image 248
Baylor Rae' Avatar asked Aug 08 '12 15:08

Baylor Rae'


People also ask

What is stub 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.

What is the difference between stubs and mocks in Ruby testing?

Stub: A class or object that implements the methods of the class/object to be faked and returns always what you want. Mock: The same of stub, but it adds some logic that "verifies" when a method is called so you can be sure some implementation is calling that method.

How do I run an RSpec on a specific file?

To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.

What is RSpec double?

RSpec features doubles that can be used as 'stand-ins' to mock an object that's being used by another object. Doubles are useful when testing the behaviour and interaction between objects when we don't want to call the real objects - something that can take time and often has dependencies we're not concerned with.


1 Answers

You can put it in the spec_helper instead, like this:

RSpec.configure do |config|
  config.before(:each) do
    User.any_instance.stub(:geocode) { [1,1] }
  end
end
like image 77
Oscar Del Ben Avatar answered Sep 22 '22 15:09

Oscar Del Ben