我正在尝试做一些看似简单但事实证明相当困难的事情。
我想使用 RSpec 为我放在 Rails 引擎的 lib
目录中的类编写测试。
以下是我正在使用的步骤:
rails plugin new mygem -T --mountable --full --dummy-path=spec/dummy
然后我
cd mygem; vim mygem.gemspec
我将以下行添加到 mygem.gemspec:
s.add_development_dependency "rspec-rails"
我运行
bundle install; rails generate rspec:install
然后我编辑
~/mygem/lib/mygem/engine.rb
添加以下内容:module Mygem
class Engine < ::Rails::Engine
isolate_namespace Mygem
config.generators do |g|
g.test_framework :rspec
end
end
end
我在lib目录下创建了一个非常简单的类,
~/mygem/lib/mygem/something.rb
并添加以下内容:
module Mygem
class Something
def hi
"hi"
end
end
end
创建一个测试文件
~/mygem/spec/something_spec.rb
然后添加以下内容:
require 'rails_helper'
describe Mygem::Something do
it 'says hi' do
s = Mygem::Something.new
expect(s.hi).to eq('hi')
end
end
繁荣,我得到以下输出:
rspec
~/Documents/mygem/spec/rails_helper.rb:3:in `require': cannot load such file -- ~/Documents/mygem/config/environment (LoadError)
from ~/Documents/mygem/spec/rails_helper.rb:3:in `<top (required)>'
from ~/Documents/mygem/spec/something_spec.rb:1:in `require'
from ~/Documents/mygem/spec/something_spec.rb:1:in `<top (required)>'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `load' from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `block in load_spec_files'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `each'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `load_spec_files'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:102:in `setup'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:88:in `run'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:73:in `run'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:41:in `invoke'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/exe/rspec:4:in `<top (required)>'
from ~/.rvm/gems/ruby-2.2.2/bin/rspec:23:in `load'
from ~/.rvm/gems/ruby-2.2.2/bin/rspec:23:in `<main>'
from ~/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in `eval'
from ~/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in `<main>'
关于我可能做错了什么的任何提示?
提前致谢!
最佳答案
看起来您的 rails_helper 正在寻找要加载的 environment.rb 文件,该文件在 Rails 引擎中不存在。但是,它确实存在于您的虚拟应用程序中,这正是 RSpec 所针对的。
尝试将其添加到 rails_helper 文件的顶部:
require File.expand_path("../dummy/config/environment.rb", __FILE__)
关于ruby-on-rails - 使用 RSpec 在 Rails 引擎中测试代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32082637/