问题
I followed along with Ryan Bates' tutorial on sortable table columns.
I attempted to write a spec for the ApplicationHelper
, but the #link_to
method fails.
Here is my spec:
require "spec_helper"
describe ApplicationHelper, type: :helper do
it "generates sortable links" do
helper.sortable("books") #just testing out, w/o any assertions... this fails
end
end
Here is the output from running the spec:
1) ApplicationHelper generates sortable links
Failure/Error: helper.sortable("books") #just testing out, w/o any assertions... this fails
ActionController::UrlGenerationError:
No route matches {:sort=>"books", :direction=>"asc"}
# ./app/helpers/application_helper.rb:5:in `sortable'
app/helpers/application_helper.rb(sortable method)
module ApplicationHelper
def sortable(column, title = nil)
title ||= column.titleize
direction = (column == params[:sort] && params[:direction] == "asc") ? "desc" : "asc"
link_to title, :sort => column, :direction => direction
end
end
回答1:
the error is happening because in your test, Rails doesn't know what's the controller/action for the url, in the way that you are generating the url, it will append {:sort => column, :direction => direction} to the current request params, but because there are not params, it will fail, so a simple way to fix it is:
describe ApplicationHelper, type: :helper do
it "generates sortable links" do
helper.stub(:params).and_return({controller: 'users', action: 'index'})
helper.sortable("books") #just testing out, w/o any assertions... this fails
end
end
and update your helper like this:
module ApplicationHelper
def sortable(column, title = nil)
title ||= column.titleize
direction = (column == params[:sort] && params[:direction] == "asc") ? "desc" : "asc"
link_to title, params.merge(:sort => column, :direction => direction)
end
end
回答2:
Honestly, the easiest way is to pass the request_params
into the helper
rather than trying to stub out your params exactly like they are when running as a full stack.
def sortable(column, request_params, title = nil)
title ||= column.titleize
direction = (column == params[:sort] && params[:direction] == "asc") ? "desc" : "asc"
link_to title, request_params
end
来源:https://stackoverflow.com/questions/22072019/how-to-write-an-rspec-test-for-ryan-bates-helper-from-screencast-228