在Rakefile中包含spec_helper

时间:2018-10-01 19:48:54

标签: rspec rake rake-task rspec3

在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)

建议不要读取.rpsecspec_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

如何纠正此问题?

1 个答案:

答案 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