如何告诉database_cleaner不在特定的一组rspec测试中运行

时间:2016-09-19 08:28:22

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

我有一组有序的测试,可以模仿用户操作并依赖于另一个。

如何配置database_cleaner在这些有序测试中间不清理数据库?

/spec/support/database_cleaner.rb:

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end

测试样本:

RSpec.describe Conversation, type: :model, order: :defined do
  context 'by default' do
    before :context do
      @alice = create :user
      @bob = create :user
      @subject = 'subject'
      @body = 'body'
      @conversation = @alice.send_message(@bob, @subject, @body)
    end

    it 'should have the subject it was opened with' do
      expect(@conversation.subject).to eq @subject
    end

    it 'should have one message upon opening' do
      expect(@conversation.messages.count).to eq 1
    end

    it 'should be initiated by @alice' do
      expect(@conversation.initiator).to eq @alice
    end

    it 'should be received by @bob' do
      expect(@conversation.recipient).to eq @bob
    end

    it 'should have two messages when bob sends a new message' do
      @conversation.add_message(@bob, 'This is my second message')
      expect(@conversation.messages.count).to eq 2
    end
end

1 个答案:

答案 0 :(得分:0)

修正了它。我的测试是随机运行的,除了这些测试,它们都有order: :defined标记。因此,我在unless中的config.before语句中添加了support/database_cleaner.rb条件。

现在看起来像这样:

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end