RSpec View testing: How to modify params?

rspec, ruby-on-rails

Solution

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.

Problem

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.

Original source