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: nil、メタデータ タグが指定されていない場合、spec_helper の (または false) ブロックが実行されないことです。例間でクリーニングする前に :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 に答える