【问题标题】:Rspec Does Not Recognize Rails's content_tagRspec 不识别 Rails 的 content_tag
【发布时间】:2015-01-28 22:39:49
【问题描述】:

我有一个 Rails (4.2) 助手,我正在尝试使用 Rspec 3 进行单元测试。

# app/helpers/nav_helper.rb
module NavHelper
  def nav_link(body, url, li_class: "", html: {})
    li_class += current_page?(url) ? " active" : ""

    content_tag(:li, class: li_class) do
      link_to(body, url, html)
    end
  end
end

# spec/helpers/nav_helper_spec.rb
require 'spec_helper'
describe NavHelper do
  describe "#nav_link" do
    it "creates a correctly formatted link" do
      link = nav_link("test", "www.example.com/testing")
      ...
    end
  end
end

当我运行测试时,这会引发以下错误:

 Failure/Error: link = nav_link("test", "www.example.com/testing")
 NoMethodError:
   undefined method `content_tag' for #<RSpec::ExampleGroups::NavHelper::NavLink:0x007fe44b98fee0>
 # ./app/helpers/nav_helper.rb:5:in `nav_link'

Rails 助手似乎不可用,但我不确定如何包含它们。无论如何,如何测试使用 content_tag 的辅助方法?

更新

添加include ActionView::Helpers::TagHelper 会引发以下错误

uninitialized constant ActionView (NameError)

【问题讨论】:

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


    【解决方案1】:

    您需要在您的NavHelper(在本例中为TagHelper)中包含包含content_tag 方法的帮助程序:

    module NavHelper
      include ActionView::Helpers::TagHelper
    
      # ...
    end
    

    最好只包含使事情正常工作所需的帮助程序,因为它可以清楚地表明您在帮助程序中使用了 Rails/ActionView 的哪些部分。

    编辑:为什么需要这样做?

    当您测试帮助程序时,您是在将其与 Rails 的其余部分隔离开来进行测试。这就是 RSpec 抱怨该方法不可用的原因 - 它实际上不存在!

    【讨论】:

    • 这会引发错误uninitialized constant NavHelper::ActionView (NameError),无论我是按照您的建议将它包含在模块中还是包含在测试本身中。
    • ActionView 前面添加:: 可以解决这个问题吗?
    • 它改变了它。现在它说:uninitialized constant ActionView。抱歉我的回复延迟!
    【解决方案2】:

    问题是我的规范的主要内容。我将require 'spec_helper' 更改为require 'rails_helper',一切正常。

    这不是第一次咬我,但它是最难的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多