在Rspec 3中,包括spec/spec_helper.rb
文件的首选方法是在.rpsec
文件中添加标志:
--require spec_helper
无需在每个_spec
文件的顶部添加引用:
# include 'spec/spec_heler' <-- removed
describe FooController do
end
但是,当我尝试通过Rake运行Rspec测试时,出现错误:
$ rake test
Traceback (most recent call last):
/Users/<user>/Projects/sinatra/mod/spec/app/controllers/foo_controller_spec.rb:1:in `<top (required)>': uninitialized constant FooController (NameError)
rake aborted!
Command failed with status (1)
Tasks: TOP => test
(See full trace by running task with --trace)
建议不要读取.rpsec
和spec_helper
文件。
Rakefile
的内容:
require 'rake/testtask'
Rake::TestTask.new do |t|
t.pattern = "spec/**/*_spec.rb"
end
spec/spec_helper.rb
的内容:
require 'rack/test'
require 'rspec'
require File.expand_path '../../app.rb', __FILE__
RSpec.configure do |config|
# rack
config.include Rack::Test::Methods
...
end
如何纠正此问题?
答案 0 :(得分:0)
我需要更改Rakefile
:
require 'rspec/core/rake_task'
task :default => :spec
RSpec::Core::RakeTask.new(:spec) do |t|
t.pattern = "spec/**/*_spec.rb"
end
我还需要更改spec/spec_helper.rb
文件:
# added
require 'rubygems'
require 'bundler/setup'
# existing
require 'rack/test'
require 'rspec'
require File.expand_path '../../app.rb', __FILE__
RSpec.configure do |config|
# rack
config.include Rack::Test::Methods
...
end
从rspec
运行测试时:
$ rspec
...
Finished in 0.07952 seconds (files took 0.63445 seconds to load)
15 examples, 0 failures, 1 pending
从rake
运行测试时:
$ rake
/Users/<user>/.rbenv/versions/2.3.3/bin/ruby -I/Users/<user>/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rspec-support-3.8.0/lib:/Users/<user>/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rspec-core-3.8.0/lib /Users/<user>/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rspec-core-3.8.0/exe/rspec --pattern spec/\*\*/\*_spec.rb
...
Finished in 0.08885 seconds (files took 0.70133 seconds to load)
15 examples, 0 failures, 1 pending
但是不确定为什么要添加$LOAD_PATH
。