如何在Rails 4中测试助手?

时间:2016-06-18 23:53:20

标签: ruby-on-rails ruby ruby-on-rails-4 rspec

使用此ApplicationHelper

class ApplicationHelper 
  def my_method
    link_to 'foo', 'bar'
  end  
end

application_helper_spec

require 'rails_helper'

describe ApplicationHelper do
  describe 'links' do 
    it 'should call a helper method' do
      expect(helper.my_method).to eq("<a href='bar'>foo</a>")
    end
  end
end

我无法像latest documentation I can find on Rails helper specs那样按照我的预期开始工作。 (文档适用于Ruby 3,我使用的是4.)似乎没有helper对象:

undefined local variable or method `helper' for #<RSpec::ExampleGroups::ApplicationHelper::Links:0x007fda1895c2f8>

如果我这样做:

require 'rails_helper'
include ApplicationHelper

describe ApplicationHelper do
  describe 'links' do 
    it 'should call a helper method' do
      expect(my_method).to eq("<a href='bar'>foo</a>")
    end
  end
end

现在正确调用my_method但未定义link_to

undefined method `link_to' for #<RSpec::ExampleGroups::ApplicationHelper::Links:0x007fda1c4c3e90>

(后一种情况与我在config.include ApplicationHelper中定义rails_helper的情况相同。)

显然,规范环境不包括所有标准的Rails助手。我在这做错了什么?

2 个答案:

答案 0 :(得分:5)

您需要启用{"Alex":21,"Grek":34.4,"Mark":54.22} 选项,或明确设置测试类型,例如:

infer_spec_type_from_file_location!

答案 1 :(得分:1)

我认为Andy Waite's answer关于在您的规范中定义type: :helper是正确的,因为它将解决您的undefined local variable or method 'helper'问题。

然而,关于“我如何在Rails 4中测试助手?”的首要问题,特别是你的方法似乎只是打电话给ActionView::Helpers::UrlHelper#link_to,假设你不想覆盖这在功能规范中并且想要单独测试它,考虑如果你想测试“调用#my_method返回包含用于foo bar链接的HTML的字符串”,the link_to tests for UrlHelper itself将确认调用{ {1}}将返回link_to 'foo', 'bar'

所以,我建议你将你的规格提高一级,说你要测试“调用"<a href='bar'>foo</a>"给我一个foo bar的链接(以任何方式Rails把我链接回链接)”:

#my_method

就个人而言,我认为这种方法没有足够的逻辑来保证在辅助规范中单独进行测试,并且你最好在功能规范中覆盖它,我假设你要测试它链接的显示,或点击它以查看发生了什么等。

相关问题