我跟着Ryan Bates' tutorial on sortable table columns。
我尝试为ApplicationHelper
编写规范,但#link_to
方法失败。
这是我的规格:
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
以下是运行规范的输出:
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(可排序方法)
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
答案 0 :(得分:5)
错误正在发生,因为在你的测试中,Rails不知道url的控制器/动作是什么,就像你生成url一样,它会附加{:sort => column,:direction =>当前请求参数的方向},但因为没有参数,它会失败,所以解决它的一个简单方法是:
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
并像这样更新您的助手:
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
答案 1 :(得分:0)
老实说,最简单的方法是将request_params
传递到helper
中,而不是像在完整堆栈中一样尝试将参数完全存根。
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