如何从屏幕录像#228为Ryan Bates的助手写一个RSpec测试?

时间:2014-02-27 14:51:45

标签: ruby-on-rails rspec

我跟着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

2 个答案:

答案 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