即使 RSpec 在 Rails 控制台中加载,它也不会加载我的类 [英] RSpec doesn't load my class even though it loads in the Rails console
问题描述
我在 app/models/parser
中有一个名为 data.rb
的类,其中包含内容:
I've got a class inside app/models/parser
called data.rb
with contents :
class Parser::Data
def method1
end
end
在这一点上没什么特别的.我试图在实现太多之前为它编写一个测试,只是为 Rails 安装了默认的 RSpec.
Nothing fancy at this point. I'm trying to write a test for it before implementing too much, just did default RSpec install for Rails.
我的 RSpec 文件在 spec/models/parser/data_spec.rb
中,到目前为止是非常基本的:
My RSpec file is in spec/models/parser/data_spec.rb
and is very basic so far:
require 'spec_helper.rb'
describe Parser::Data do
let(:parser) { Parser::Data.new }
end
当我运行测试时出现此错误:
When I run the test I get this error:
spec/models/parser/data_spec.rb:3:in `<top (required)>': uninitialized constant Parser (NameError)
我尝试将 module Parser
放在同一目录 app/models/parser
中的 Data
类周围,我也尝试移动它到 lib/parser
做相同的模块包装类,并将 lib/parser
添加到 application.rb
中自动加载,但到目前为止没有任何效果.
I tried placing module Parser
around the Data
class in the same directory app/models/parser
, also I've tried moving it to lib/parser
doing the same module wrapping class, and added lib/parser
to autoload in the application.rb
but nothing has worked so far.
我做错了什么?
推荐答案
require 'rails_helper'
而不是 spec_helper
.只需要 spec_helper
为我重现了这个问题,并且需要 rails_helper
修复它.在此处详细了解 spec_helper
与 rails_helper
(包括性能影响):spec/rails_helper.rb 与 spec/spec_helper.rb 有何不同?我需要吗?
require 'rails_helper'
instead of spec_helper
. Requiring only spec_helper
reproduces the issue for me, and requiring rails_helper
fixes it. More on spec_helper
vs. rails_helper
(including performance implications) here: How is spec/rails_helper.rb different from spec/spec_helper.rb? Do I need it?
我通过使用 bundle exec rspec
运行 RSpec 重现了这个问题.如果我使用 bin/rspec
(这是由 spring-commands-rspec gem 生成的 binstub)运行 RSpec,它并不关心我需要哪个帮助文件.我猜弹簧会更急切地加载.
I reproduced the problem by running RSpec with bundle exec rspec
. If I run RSpec with bin/rspec
(that's a binstub generated by the spring-commands-rspec gem) it doesn't care which helper file I require. I guess spring loads more eagerly.
这篇关于即使 RSpec 在 Rails 控制台中加载,它也不会加载我的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!