如何从截屏视频 #228 中为 Ryan Bates 的助手编写 RSpec 测试? [英] How to write an RSpec test for Ryan Bates' helper from screencast #228?
问题描述
我尝试为 ApplicationHelper
编写规范,但 #link_to
方法失败.
I attempted to write a spec for the ApplicationHelper
, but the #link_to
method fails.
这是我的规格:
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(可排序方法)
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
推荐答案
发生错误是因为在您的测试中,Rails 不知道 url 的控制器/操作是什么,以您生成 url 的方式,它会将 {:sort => column, :direction => direction} 附加到当前请求参数,但是因为没有参数,它会失败,所以一个简单的修复方法是:
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
这篇关于如何从截屏视频 #228 中为 Ryan Bates 的助手编写 RSpec 测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!