4

如何标记示例组,以便在每个示例之间不清理数据库,而是在整个组之前和之后清理数据库?并且未标记的规范应该在每个示例之间清理数据库。

我想写:

describe 'my_dirty_group', :dont_clean do
  ...
end

所以在我的 spec_helper.rb 我放:

  config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:suite, dont_clean: true) do
    DatabaseCleaner.clean
  end

  config.after(:suite, dont_clean: true) do
    DatabaseCleaner.clean
  end

  config.before(:each, dont_clean: nil) do
    DatabaseCleaner.start
  end

  config.before(:each, dont_clean: nil) do
    DatabaseCleaner.clean
  end

问题是dont_clean: nilspec_helper 中的(或错误的)块在未指定元数据标记时不会运行。在清理示例之前是否有另一种方法来检查 :dont_clean 的存在?

4

2 回答 2

3

概括

您可以在整个示例块上设置自定义元数据,然后访问 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 
于 2015-04-03T06:20:11.050 回答
0

您可以检查example.metadata块内部,尽管我无法弄清楚如何为before(:suite)

于 2013-10-18T14:46:29.683 回答