I have the following file struture in my Ruby-on-Rails project, for the specs:
/spec
/msd
/service
service_spec.rb
/support
/my_module
requests_stubs.rb
My request_stubs.rb
have:
module MyModule::RequestsStubs
module_function
def list_clients
url = "dummysite.com/clients"
stub_request(:get, url).to_return(status: 200, body: "clients body")
end
end
In my service_spec.rb
I have:
require 'rails_helper'
require 'support/my_module/requests_stubs'
...
because I only want the method available in this file.
The problem is that when running the tests I call the method MyModule::RequestsStubs.list_clients
in the service_spec.rb
file, I get the following error:
Failure/Error:
stub_request(:get, url).to_return(status: 200, body: "clients body")
NoMethodError:
undefined method `stub_request' for MyModule::RequestsStubs:Module
when accessing the WebMock method stub_request
.
The WebMock gem is installed and is required in the spec_helper.rb
file.
Why does the error occurs? It looks like it can't access the WebMock gem, or don't know how to access it. Any ideas on how to solve it?
stub_request
is defined in the WebMock
namespace, so you have to use WebMock.stub_request
. To make it available globally, you need to add include WebMock::API
to your rails_helper.
Even better, include webmock/rspec
instead of just webmock
-- it will take care of including the WebMock::API
as well as setting up the webmock RSpec matchers.
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