Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Rspec - stub params

I created some public method in controller which does some work.

 def current_service
    service_name = params[:controller].gsub('api/v1/', '').gsub(%r{/.+}, '')
 end

I would like to test this method using RSpec but I dont't know how can I stub params. How should I do that?

like image 420
mike927 Avatar asked Jul 28 '16 07:07

mike927


2 Answers

If this is a controller spec, you should be able to do something like this:

allow(controller).to receive(:params).and_return({controller: 'a value'})

Alternatively, move the params[:controller] statement to a separate method and stub that in your spec.

like image 178
Codebeef Avatar answered Oct 21 '22 08:10

Codebeef


For strong parameters you can stub them as following:

params = ActionController::Parameters.new(foo: 'bar')
allow(controller).to receive(:params).and_return(params)
like image 4
rya brody Avatar answered Oct 21 '22 07:10

rya brody