views:

595

answers:

2

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.

+2  A: 

That's because you shouldn't be using params in your views.
The best way I see it to use an helper.

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

And in one of your helper files

def sorted_by
    params[:sorted_by].capitalize
end

Then you can test your helpers quite easily (because in helpers tests, you can define the params request.

Damien MATHIEU
Not what I expected, but it solved my problem AND improved my application. Thanks!
sebastiangeiger
+2  A: 

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 {}
fernyb