我跟在Ryan Bates关于可排序列的教程后面。
我试图为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
发布于 2014-03-08 06:22:43
发生此错误是因为在您的测试中,Rails不知道url的控制器/操作是什么,以生成url的方式,它将在当前请求params中附加{:=>列,:=>方向},但是由于没有对角,它将失败,因此修复它的一个简单方法是:
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
发布于 2019-07-30 22:16:33
老实说,最简单的方法是将request_params
传递到helper
中,而不是像作为一个完整堆栈运行时那样,尝试将您的params留出。
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
复制相似问题