概括
您可以在整个示例块上设置自定义元数据,然后访问 RSpec 配置中的元数据以self.class.metadata
用于条件逻辑。
代码
使用这些 gem 版本:
$ bundle exec gem list | grep -E '^rails |^rspec-core |^database'
database_cleaner (1.4.0)
rails (4.2.0)
rspec-core (3.2.0)
以下对我有用:
文件:spec/spec_helper.rb
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with(:truncation)
end
config.before(:all) do
# Clean before each example group if clean_as_group is set
if self.class.metadata[:clean_as_group]
DatabaseCleaner.clean
end
end
config.after(:all) do
# Clean after each example group if clean_as_group is set
if self.class.metadata[:clean_as_group]
DatabaseCleaner.clean
end
end
config.before(:each) do
# Clean before each example unless clean_as_group is set
unless self.class.metadata[:clean_as_group]
DatabaseCleaner.start
end
end
config.after(:each) do
# Clean before each example unless clean_as_group is set
unless self.class.metadata[:clean_as_group]
DatabaseCleaner.clean
end
end
end
文件:spec/models/foo_spec.rb
require 'spec_helper'
describe 'a particular resource saved to the database', clean_as_group: true do
it 'should initially be empty' do
expect(Foo.count).to eq(0)
foo = Foo.create()
end
it 'should NOT get cleaned between examples within a group' do
expect(Foo.count).to eq(1)
end
end
describe 'that same resource again' do
it 'should get cleaned between example groups' do
expect(Foo.count).to eq(0)
foo = Foo.create()
end
it 'should get cleaned between examples within a group in the absence of metadata' do
expect(Foo.count).to eq(0)
end
end