ruby - rspec-之前(:all) Hook ignored when running all tests

标签 ruby rspec

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) 钩子(Hook)并尝试在每个示例中填充数据库一个...有什么想法吗?

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

顺便说一句,它不是 rails

最佳答案

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

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

我建议您将 before(:all) 更改为 before(:each)

关于ruby - rspec-之前(:all) Hook ignored when running all tests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28596164/

相关文章:

ruby-on-rails - Rails - 使页面仅对管理员可见

ruby-on-rails - 简化格式化电话号码的代码

ruby-on-rails - 具有序列化字段的工厂女孩

ruby-on-rails - 为什么我的 Rspec 长度验证测试失败? (rails/guard/rspec)

ruby-on-rails - 如何在 Rspec/Capybara 测试中访问 FactoryGirl 生成的用户的虚拟属性?

ruby - hash值与 `<<`算子的交互

javascript - 您如何抓取字段以进行自动标记?

ruby-on-rails - 从模块设置类变量

ruby - 为什么这个 rspec 测试会为 nil :NilClass"error? 抛出一个 "undefined method ` 调用

ruby-on-rails - Rails 3 +Devise + RSpec : undefined method 'visit'