【问题标题】:How to require modules in app/lib folder to rspec in Rails 5如何在 Rails 5 中将 app/lib 文件夹中的模块要求为 rspec
【发布时间】:2017-10-24 07:07:56
【问题描述】:

我将模块移至

app/lib/parsers

文件夹。

模型类响应模块方法,但是当我尝试时

rspec
I have issue

Failure/Error: include MainModule::Submodule

NameError:
uninitialized constant ModelName::MainModule

module in lib/parsers looks like this

Module Parsers
  Module Parser1
    def foo
    end
end
  Module Parser2

   def bar
   end
 end
end

第一个模型通过这种方式包含第一个解析器

Class Model1 < ApplicationRecord
  include Parsers::Parser1
end

第二个也是一样 在 Rspec 中要求这些模块的最佳方法是什么?

【问题讨论】:

  • 只要 FQN 与路径匹配,它们应该会自动加载,无需任何额外步骤。显示一些代码(模块,它所在的路径以及如何包含它)
  • 添加了一些代码

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


【解决方案1】:

要求这些模块的最佳方法是什么

使用 rails 的自动加载机制。把你的Parsers::Parser1 放到app/lib/parsers/parser1.rbParsers::Parser2app/lib/parsers/parser2.rb。看看模块的全名如何反映它的存储位置?这就是 rails 能够找到它的方式。

或者您可以明确要求该文件

# my_spec.rb
require_dependency Rails.root.join('app', 'lib', 'parsers')

RSpec.describe ... 

【讨论】:

  • 第二个很有帮助,非常感谢。第一个不是。
  • @zOs0:但第一个是你应该采取的方式。 rails 指南有一个很大的红色警告“require_dependency 应该很少需要。类名和文件路径应该匹配”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多