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

Ken*_*ien 2 rspec ruby-on-rails

我跟着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
Run Code Online (Sandbox Code Playgroud)

以下是运行规范的输出:

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'
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

gui*_*eva 5

错误正在发生,因为在你的测试中,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
Run Code Online (Sandbox Code Playgroud)

并像这样更新您的助手:

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
Run Code Online (Sandbox Code Playgroud)