ruby-on-railsrspecstubruby-grapegrape-api

Cannot stub Rails.env inside Grape::API class


i'm trying to stub anything that inside this class:

module V1
    class API < Grape::API    
      use V1::Middleware::ApiLogger if Rails.env.production?

and after in the spec:

allow(Rails).to receive(:env).and_return(double(production?: true))

or

allow(Rails.env).to receive(:production?).and_return(true)

or

allow(Rails).to receive(:env) { "production".inquiry }

and

expect do
  get "/api/v1/profiles/#{profile_alex.id}"
end.to change(ApiLog, :count).by 1

Nothing is working, even stubbing instance method inside API class won't work

Did anybody has faced same problem?


Solution

  • I've found the problem.

    This was related to how the Grape preloads API class, it uses mount method that runs when the code is loaded and stub was running after the conditions, so the checks for environment shall go inside Middleware methods.