如何为RSpec编写自定义rake任务?

时间:2011-09-13 06:33:46

标签: ruby rspec2

在我的Rake文件中:

require 'rspec/core/rake_task'

desc 'Default: run specs.'
task :default => :spec

desc "Run specs"
RSpec::Core::RakeTask.new do |task|
    task.pattern = "**/spec/*_spec.rb"
    task.rspec_opts = Dir.glob("[0-9][0-9][0-9]_*").collect { |x| "-I#{x}" }.sort
    task.rspec_opts << '-r ./rspec_config'
    task.rspec_opts << '--color'
    task.rspec_opts << '-f documentation'
end

在rspec_config.rb

RSpec.configure {|c| c.fail_fast = true}

我的文件结构:

|-- 001_hello
|   |-- hello1.rb
|   `-- spec
|       `-- hello_spec.rb
|-- 002_hello
|   |-- hello2.rb
|   `-- spec
|       `-- hello_spec.rb
|-- 003_hello
|   |-- hello3.rb
|   `-- spec
|       `-- hello_spec.rb
|-- Rakefile
`-- rspec_config.rb

当rake任务运行时,它将按顺序对上述文件结构执行操作。 如何确保如果'001_hello'失败则不应该运行'002_hello'?

目前它以逆序运行,即。 '003_hello'然后'002_hello'然后'001_hello'。

2 个答案:

答案 0 :(得分:6)

您需要修改任务模式以使文件按特定顺序运行。例如:

RSpec::Core::RakeTask.new do |task|
  task.pattern = Dir['[0-9][0-9][0-9]_*/spec/*_spec.rb'].sort
  task.rspec_opts = Dir.glob("[0-9][0-9][0-9]_*").collect { |x| "-I#{x}" }
  task.rspec_opts << '-r ./rspec_config --color -f d'
end

这将按字母顺序运行与###_*/spec/*_spec.rb匹配的所有文件。

答案 1 :(得分:1)

我不明白执行顺序是否真的对你有用。

无论如何,如果应用程序应该在出错时退出,为什么不提出异常呢?

修改
由于执行顺序对您有意义,我认为

task.rspec_opts = Dir.glob("[0-9][0-9][0-9]_*").collect { |x| "-I#{x}" }.sort

不会做你期望的。

然后可能没有特定顺序包含该文件,因此您应该以编程方式单独调用每个文件并进行检查。

HTH