Betjamin Richards
Betjamin Richards

Reputation: 911

Testing link_to without path in helper using Rspec

Using the tip here I have built a method in a helper module like so:

describe ExampleHelper do
  def build_link
    link_to "RSS feed", params.merge(:format => :rss), :class => "feed_link"
  end
end

However, when I test this method I get the following error:

 Failure/Error: subject { helper.build_link }
 ActionController::UrlGenerationError:
   No route matches {:action=>"index", :foo=>"bah", :foobah=>["1", "2", "3"], :results_per_page=>"25"}
 # /Users/tombrammar/.rvm/gems/ruby-2.1.10@example/gems/actionpack-4.2.6/lib/action_dispatch/journey/formatter.rb:46:in `generate'
 # /Users/tombrammar/.rvm/gems/ruby-2.1.10@example/gems/actionpack-4.2.6/lib/action_dispatch/routing/route_set.rb:721:in `generate'
 # /Users/tombrammar/.rvm/gems/ruby-2.1.10@example/gems/actionpack-4.2.6/lib/action_dispatch/routing/route_set.rb:752:in `generate'
 # /Users/tombrammar/.rvm/gems/ruby-2.1.10@example/gems/actionpack-4.2.6/lib/action_dispatch/routing/route_set.rb:799:in `url_for'
 # /Users/tombrammar/.rvm/gems/ruby-2.1.10@example/gems/actionpack-4.2.6/lib/action_dispatch/routing/url_for.rb:156:in `url_for'
 # /Users/tombrammar/.rvm/gems/ruby-2.1.10@example/gems/actionview-4.2.6/lib/action_view/routing_url_for.rb:94:in `url_for'
 # /Users/tombrammar/.rvm/gems/ruby-2.1.10@example/gems/actionview-4.2.6/lib/action_view/helpers/url_helper.rb:181:in `link_to'

It seems that because I'm testing within the helper it can't determine what controller to use and therefore how to build the url.

Can anyone help me understand how to fix this? I.e. perhaps I can stub the controller the helper rspec?

Upvotes: 1

Views: 1928

Answers (1)

User128848244
User128848244

Reputation: 3470

This is a dirty trick if you are using params like above.

allow(helper).to receive(:params).and_return(_recall: { controller: 'homes' })

Also here is another way to do it that is a quick way to get the job done.

https://stackoverflow.com/a/22265920/1431800

Upvotes: 2

Related Questions