[英]How do I test helpers in Rails 4?
使用此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
正如我在Rails助手规范中可以找到的最新文档所期望的那样,我很难使事情正常进行。 (该文档适用于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>
(后一种情况与我在rails_helper
定义config.include ApplicationHelper
情况rails_helper
。)
显然,规范环境并不包括所有标准的Rails帮助器。 我在这里做错了什么?
您需要启用infer_spec_type_from_file_location!
选项,或显式设置测试类型,例如:
describe ApplicationHelper, type: :helper do ... end
我认为安迪·怀特(Andy Waite)关于定义type: :helper
的答案是正确的,因为它将解决您undefined local variable or method 'helper'
问题。
但是,关于“如何在Rails 4中测试助手”这一最重要的问题,特别是假设您不想调用ActionView::Helpers::UrlHelper#link_to
,在功能说明中对此进行了介绍,并希望对其进行#my_method
测试,请考虑一下,如果要测试“调用#my_method
返回的字符串包含包含foo bar链接的HTML”, 则针对UrlHelper
本身的link_to
测试将确认调用link_to 'foo', 'bar'
将返回"<a href='bar'>foo</a>"
。
因此,我建议将您的规格上移一个级别,说您想测试一下“调用#my_method
我返回了foo bar的链接(Rails向我返回链接的任何方式)”:
require 'rails_helper'
RSpec.describe ApplicationHelper, type: :helper do
describe '#my_method' do
it 'returns a foo bar link' do
expect(helper).to receive(:link_to).with('foo', 'bar')
helper.my_method
end
end
end
不过,就我个人而言,我认为此方法没有足够的逻辑来保证在帮助程序规范中进行单独测试,因此最好在某个功能规范中进行介绍,我假设您将对此功能进行测试。链接,或单击它以查看会发生什么,等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.