Liondancer
Liondancer

Reputation: 16469

Stub controller method when performing web request with Rspec

How can I stub either the controller method or the helper method that occurs upon making the request?

I have a test that makes a web request. The request goes to the controller which also calls a helper method. In the example below, I want to stub the return value of service_config for my testing purposes because service_config comes from AdminsHelper and performs an actual API request to a service.

I'm a bit new to Rspec and these type of testing practices so I might also be headed the wrong way in proper testing of this web request

Test:

context 'when an invalid parameter is specified' do
  it 'should return a hash of size 0' do
    get '/admins/configs/poop'
    json = JSON.parse(response.body)
    expect(json).to be == ({})
  end
end

Controller:

class AdminsController < ApplicationController
  include AdminsHelper

  def configs
    response = service_config
    render json: response, status: 200
  end
end

Upvotes: 0

Views: 603

Answers (1)

spickermann
spickermann

Reputation: 106812

I would expect that RSpecs any instance mock would wotk in this case.

context 'when an invalid parameter is specified' do
  it 'should return a hash of size 0' do
    allow_any_instance_of(AdminsController).to receive(:service_config).and_return({})

    get '/admins/configs/poop'

    json = JSON.parse(response.body)
    expect(json).to eq({})
 end

end

Upvotes: 2

Related Questions