我试图为编写规范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
发生错误是因为在测试中,Rails不知道该URL的控制器/动作是什么,在生成URL的方式中,它将{{sort => column,:direction => 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句