How to write an RSpec test for Ryan Bates' helper from screencast #228?

白昼怎懂夜的黑 提交于 2020-01-04 13:37:21

问题


I followed along with Ryan Bates' tutorial on sortable table columns.

I attempted to write a spec for the ApplicationHelper, but the #link_to method fails.

Here is my spec:

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

Here is the output from running the spec:

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(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

回答1:


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



回答2:


Honestly, the easiest way is to pass the request_params into the helper rather than trying to stub out your params exactly like they are when running as a full stack.

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/how-to-write-an-rspec-test-for-ryan-bates-helper-from-screencast-228

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!