1

我有一系列相当复杂的测试,以更简单的形式复制如下:

# Credit cards that should succeed; totally opening to other ways of running this loop, if it's what's causing the error! It's just the only thing I thought of to be DRY
["2134", "1234"].each do |card|
  describe "enter card number", job: true do
    before do
      fill_in "card_number", with: card
    end

    it "should create a record" do
      Record.count.should == 1
    end
  end
end

# Credit card that should fail
# Just the one number here
  describe "enter card number" do
    before do
      fill_in "card_number", with: "5678"
    end

    it "should create a record" do
      Record.count.should == 0
    end
  end

在配置中我需要关闭,use_transactional_fixtures因为这些是基于 javascript 的测试,而事务性装置对我不起作用。所以我尝试像这样实现数据库清理器(使用 Sucker Punch gem 指令https://github.com/brandonhilkert/sucker_punch,因为我最终还需要测试 gem):

  # Database cleaner set up below
  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  # Clean up all jobs specs with truncation
  config.before(:each, job: true) do
    DatabaseCleaner.strategy = :truncation
  end

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

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

问题是这无济于事:

  • 对于应该成功的信用卡(每个循环),第一次通过,但随后都失败,因为Record.count不断构建
  • 对于应该失败的信用卡,它会失败,因为在运行测试时,Records测试数据库中已经有

基本上,它通过的唯一方法是在 a 中强制清洁before(:all)(技巧before也没有)after

 # Credit cards that should succeed
    ["2134", "1234"].each do |card|
      describe "enter card number", job: true do

        before(:all) do
          Record.destroy_all
        end

        before do
          # did not work to put the destroy here 
          fill_in "card_number", with: card
        end

        it "should create a record" do
          Record.count.should == 1
        end

        # did not work to put the destroy here 
        # after do
        #  Record.destroy_all
        # end
      end
    end

# Credit card that should fail
  describe "enter card number" do
    before do
      # On this one, the Record.destroy_all could have gone anywhere
      Record.destroy_all 
      fill_in "card_number", with: "5678"
    end

    it "should create a record" do
      Record.count.should == 0
    end
  end

如何正确设置数据库清理器?还是我应该这样做before(:all)

4

1 回答 1

0

首先,database_cleaner你用的是哪个版本的?

如果你查看 gem 的文档,你会看到一些不同的东西:

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

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end

另外,我不确定这是否会按您的预期工作:

   ["2134", "1234"].each do |card|
      describe "enter card number", job: true do
        ...
      end
    end

我会找到一种不同的方法来测试这两种情况。真的有必要这样输入两个数字吗?

于 2014-12-10T14:27:28.210 回答