假设我的项目中有四个规格文件:
spec/foo/foo_one_spec.rb
spec/foo/foo_two_spec.rb
spec/baz/baz_one_spec.rb
spec/baz/baz_two_spec.rb
仅当当前规范文件不在baz目录中时,如何才能将规范文件配置为包括某个模块?
以下是一些伪代码来说明:
module Moddy
extend RSpec::SharedContext
let(:message){ 'hello' }
before{ puts message }
end
RSpec.configure do |c|
# path is pseudo-code; pretending it returns the path of the current expectation
c.include Moddy unless path.includes?('/baz/')
end
因此,在运行我的规格时,'hello'
除了文件baz_one_spec
和中的期望之外,我希望所有期望之前都将其打印到屏幕上baz_two_spec
。
如果无法做到这一点,您能告诉我如何使用标签来实现吗?内部的所有规格baz
都必须加标签,我接受这一点。
遵循Frederick Cheung的想法,我弄清楚了如何自动为目录定义元数据,然后可以有条件地将该模块包含在该元数据中。这基于rspec-rails
从文件位置推断规范类型的方式。
我正在处理两个琐碎的规范:
# spec/foo/foo_spec.rb
require 'spec_helper'
describe 'Foo' do
it 'printed something before the test ran' do
expect(1).to eq(1)
end
end
# spec/bar/bar_spec.rb
require 'spec_helper'
describe 'Bar' do
it 'did not print anything before the test ran' do
expect(1).to eq(1)
end
end
在中spec_helper
,我复制了您的,Moddy
并使用define_derived_metadata标记了以下文件spec/foo
:
# spec/spec_helper.rb
RSpec.configure do |config|
config.define_derived_metadata(file_path: %r(spec/foo)) do |metadata|
metadata[:include_moddy] = true
end
config.include Moddy, include_moddy: true
end
该file_path
选项接受正则表达式以匹配并运行该块。这个可以接受spec/foo
,但是您的可以接受其他所有内容,或者您可以像rspec-rails
with一样在目录列表中为每个表达式创建一个表达式DIRECTORY_MAPPINGS
。
之后,这是运行规范的样子:
$ rspec
Bar
did not print anything before the test ran
Foo
hello
printed something before the test ran
Finished in 0.00101 seconds (files took 0.07205 seconds to load)
2 examples, 0 failures
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句