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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With