rspec DatabaseCleaner跳过清理,例如组元数据标记

时间:2013-06-19 12:51:07

标签: ruby-on-rails rspec database-cleaner

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

我想写:

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

问题是当未指定元数据标记时,spec_helper中的dont_clean: nil(或false)块不会运行。是否有其他方法可以检查是否存在:dont_clean在清除示例之前?

2 个答案:

答案 0 :(得分:3)

摘要

您可以在整个示例块上设置自定义元数据,然后使用self.class.metadata访问RSpec配置中的元数据,以便与条件逻辑一起使用。

代码

使用这些宝石版本:

$ 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 

答案 1 :(得分:0)

您可以查看区块内的example.metadata,但我无法弄清楚如何为before(:suite)

执行此操作