简体   繁体   中英

Rspec: how to test partial render with locals and params?

I am trying to test this part of controller with Rspec:

def popup_company
  if params[:partial].present?
    render partial: "popup_company/pages", locals: { tab_filter: params[:tab_filter] }
  end
end

Here is my controller spec to test the part mentioned above:

controller.should_receive(:render).with({
:partial => 'popup_company/pages',
:locals => {tab_filter: params[:tab_filter]}
})

However, I am getting this error:

undefined local variable or method `params'

Guys, can you, please, tell me what I should change to overcome this error. I appreciate your help!

Your params is on the spec-side code; it's just trying to be a local variable. Put in whatever you expect params[:tab_filter] to contain.

And, in general, you should not write tests - oops I mean "examples" - that merely repeat what the code says. You don't care your controller calls a partial; you care that the controller responds with HTML containing such-and-so values.

So params[:tab_filter] is in your request, so it's presumably in your get. That is, you have something like:

get :popup_company, tab_filter: 'XXXXX', partial: 'YYYYY'

in your spec. You should create a variable, random value for the tab_filter param and use that to validate the appropriate value is being passed to render. Something like

tab_filter = SecureRandom.hex(10)
get :popup_company, tab_filter: tab_filter, partial: 'YYYYY'
controller.should_receive(:render).with({
  partial: 'popup_company/pages',
  locals: { tab_filter: tab_filter } })

Alternately you could use a render_template('popup_company/pages') spec to confirm that the template is being rendered, and test for the tab filter based on the content of the rendered view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM