如何在Rails 4中测试助手?

Sas*_*lla 0 ruby rspec ruby-on-rails ruby-on-rails-4

有了这个ApplicationHelper:

class ApplicationHelper 
  def my_method
    link_to 'foo', 'bar'
  end  
end
Run Code Online (Sandbox Code Playgroud)

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

我无法按照我在Rails帮助程序规范中找到最新文档的预期工作.(文档适用于Ruby 3,我使用的是4.)似乎没有helper对象:

undefined local variable or method `helper' for #<RSpec::ExampleGroups::ApplicationHelper::Links:0x007fda1895c2f8>
Run Code Online (Sandbox Code Playgroud)

如果相反,我这样做:

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

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

undefined method `link_to' for #<RSpec::ExampleGroups::ApplicationHelper::Links:0x007fda1c4c3e90>
Run Code Online (Sandbox Code Playgroud)

(这后一种情况下是一样的,如果我定义config.include ApplicationHelperrails_helper).

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

And*_*ite 5

您需要启用该infer_spec_type_from_file_location!选项,或者显式设置测试类型,例如:

describe ApplicationHelper, type: :helper do ... end