【问题标题】:Can't access included module methods from view when running RSpec运行 RSpec 时无法从视图中访问包含的模块方法
【发布时间】:2013-09-25 15:31:30
【问题描述】:

我有一个 ProductController,它包含一个带有一些辅助方法的模块:

class ProductController < ApplicationController
  include ProductItemHelper

  def item
    @product = Product.find_by_id(params[:id])
  end
end

模块如下所示:

module ProductItemHelper

  def seoify(text)
    unless text.blank?
      "#{text.titleize} | "
    end
  end

end

然后在我看来,我这样调用辅助方法:

content_for :meta_title do
  "#{seoify(@product.title)}"
end

当我在任何环境中运行应用程序时,它都可以正常工作,但是当我尝试在 RSpec 测试中访问页面时,它会点击控制器和视图,但会出现以下错误:

undefined method `seoify' for #<#<Class:0x0000000a6a0a18>:0x0000000b726e50>

我不明白为什么。我已经测试过从控制器调用该方法,它工作正常,@product.title 在整个视图的不同点应用了几种不同的方法,所以我希望能够从视图中引用模块方法。

我是否缺少一些 RSpec 配置以使其可访问?

【问题讨论】:

  • 视图/控制器,希望它们没有混在一起
  • 看起来我需要在 RSpec 中明确包含这些方法,所以我在 spec/support 中创建了一个名为 utility.rb 的文件并将其包含在内 - 它可以工作!

标签: ruby-on-rails testing rspec


【解决方案1】:

尝试使用内置控制器的类方法helper 来要求和包含助手

class ProductController < ApplicationController
  helper :product_item

http://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper

【讨论】:

    【解决方案2】:

    this question 接受的答案让我走上了正轨,我只需要将方法包含在我的规范目录中的帮助文件中。

    【讨论】:

      猜你喜欢
      • 2015-05-25
      • 1970-01-01
      • 2022-06-11
      • 2016-11-24
      • 2014-08-16
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多