rspec - before(:all) Hook 在 运行 所有测试时被忽略

rspec - before(:all) Hook ignored when running all tests

RSpec.configure do |config|
  config.before(:suite) do
    cleaner.strategy = :truncation
    cleaner.clean_with(:truncation)
  end

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

其中一项测试:

  require 'rspec'

    describe 'Test of all Listing parameters' do
      before(:all) do
        populate_from_yaml('spec/sample_data/listing_param_filtering_data.yaml')
      end

      it 'filter by active listing' do
        params = make_params(userId: 'users-1', limit: 100)
        listings = request_shuffler(params)

        expect(listings).not_to include('listing-inactive')
        expect(listings).to include('listing-active-all-empty')
      end

      it 'filter by doorman' do
        params = make_params(userId: 'users-1', limit: 100, doorman: true)
        listings = request_shuffler(params)

        expect(listings).to match_array(['listing-param-doorman'])
      end
      # and so on
   end

当我 运行 测试指定测试名称时一切正常

rspec spec/test_spec.rb

但是如果我执行所有测试:

rspec spec

我遇到错误:

Test of all Listing parameters filter by active listing
Failure/Error: populate_from_yaml('spec/sample_data/listing_param_filtering_data.yaml')
Sequel::UniqueConstraintViolation:
    PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "agents_pkey"
DETAIL:  Key (id)=(agent-1) already exists.
Debug data ...

Test of all Listing parameters filter by doorman
Failure/Error: populate_from_yaml('spec/sample_data/listing_param_filtering_data.yaml')
Sequel::UniqueConstraintViolation:
    PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "agents_pkey"
DETAIL:  Key (id)=(agent-1) already exists.
Debug data ...

...

看起来 rspec 只是忽略了 config.around(:each) 停止清理数据库,忽略了 before(:all) 钩子并尝试在每个示例中填充一个数据库...有什么想法吗?

我正在使用 ruby-2.2.0p0 rspec-3.2.0

顺便说一句,这不是 rails

before(:all)是邪恶的,是很多人头疼的根源,所以很多rspec考虑了很多次to remove the command at all。这个块没有包裹在事务中,所以测试后数据不会回滚。您应该手动清除 after(:all) 块中的数据。

我个人的最佳做法是仅使用 before(:all) 设置环境变量、全局库配置...但永远不要使用它来访问数据库。

我建议您将 before(:all) 换成 before(:each)