Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"undefined method `stub_request'" when accessing the method in an RSpec support file

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?

like image 279
rjmAmaro Avatar asked Mar 02 '18 17:03

rjmAmaro


1 Answers

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.

like image 52
Maxim Krizhanovsky Avatar answered Nov 05 '22 05:11

Maxim Krizhanovsky