Alex Rivera | Logout

RSpec View testing: How to modify params?

Asked 2009-11-26T10:03:07.203
17

I am trying to test my views with RSpec. The particular view that is causing me troubles changes its appearance depending on a url parameter:

link_to "sort>name", model_path(:sort_by => 'name') which results in http://mydomain/model?sort_by=name

My view then uses this parameter like that:

<% if params[:sort_by] == 'name' %>
<div>Sorted by Name</div>
<% end %>

The RSpec looks like this:

it "should tell the user the attribute for sorting order" do
    #Problem: assign params[:sort_for] = 'name' 
    render "/groups/index.html.erb"
    response.should have_tag("div", "Sorted by Name")
end

I would like to test my view (without controller) in RSpec but I can't get this parameter into my params variable. I tried assign in all different flavours:

  • assign[:params] = {:sort_by => 'name'}
  • assign[:params][:sort_by] = 'name'
  • ...

no success so far. Every idea is appreciated.

Edit
Report

2 Answers

38

If its a controller test then it would be

controller.stub!(:params).and_return {}

If its a helper test then it would be:

helper.stub!(:params).and_return {}

And its a view test it would be:

view.stub!(:params).and_return {}

If you get warning like below.

Deprecation Warnings:

Using `stub` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead. Called from /home/akbarbin/Documents/Office/projects/portfolio/spec/views/admin/waste_places/new.html.erb_spec.rb:7:in `block (2 levels) in <top (required)>'.


If you need more of the backtrace for any of these deprecations to
identify where to make the necessary changes, you can configure
`config.raise_errors_for_deprecations!`, and it will turn the
deprecation warnings into errors, giving you the full backtrace.

1 deprecation warning total

Finished in 4.86 seconds (files took 4.72 seconds to load)

You can change it into

allow(view).to receive(:params).and_return({sort_by: 'name'})
answered 2009-12-01T00:37:11.447
13

Canonical answer:

To use params in views from within view specs, if your view has params[:id], then somewhere in your spec do:

controller.extra_params = { id: widget.id }

Documentation: https://rspec.info/features/6-0/rspec-rails/view-specs/view-spec

However, it is also a good idea to not reference params in your views.

To get them out of your views you could use a helper, like this:

<div>Sorted by <%= sorted_by %></div>

And in one of your helper files

def sorted_by
    params[:sorted_by].capitalize
end

Unfortunately, you really shouldn't be referencing params in helpers either. Don't reference what you don't own, ideally.

A better idea would be to use the Presenter Pattern, and a good example of a tool for that is ViewComponent.

answered 2009-11-26T10:18:15.323

Your Answer