简体   繁体   English

Rails 4:使用 RSpec 测试 rake 任务时的 PG::InFailedSqlTransaction

[英]Rails 4: PG::InFailedSqlTransaction when testing a rake task with RSpec

I am currently trying to test a rake task with RSpec.我目前正在尝试使用 RSpec 测试 rake 任务。 My Rails version is 4.2.4 and rspec-rails version is 3.3.2.我的 Rails 版本是 4.2.4,rspec-rails 版本是 3.3.2。

I've have the following in rails_helper.rb :我在rails_helper.rb 中有以下内容

ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'capybara/rspec'

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

RSpec.configure do |config|
  ...

  config.use_transactional_fixtures = false
  config.infer_spec_type_from_file_location!
  ...
end

and then spec/support/tasks.rb :然后是spec/support/tasks.rb

require 'rake'

module TaskExampleGroup
  extend ActiveSupport::Concern

  included do
    let(:task_name) { self.class.top_level_description.sub(/\Arake /, "") }
    let(:tasks) { Rake::Task }

    # Make the Rake task available as `task` in your examples:
    subject(:task) { tasks[task_name] }
  end
end

RSpec.configure do |config|
  # Tag Rake specs with `:task` metadata or put them in the spec/tasks dir
  config.define_derived_metadata(file_path: %r{/spec/tasks/}) do |metadata|
    metadata[:type] = :task
  end

  config.include TaskExampleGroup, type: :task

  config.before(:suite) do
    Rails.application.load_tasks
  end
end

my spec/support/database_cleaner.rb我的规范/支持/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.append_after(:each) do
    DatabaseCleaner.clean
  end
end

and finally, the spec:最后,规范:

require 'rails_helper'

describe "rake some:my_task", type: :task do

  # This test passes
  it 'preloads the Rails environment' do
    expect(task.prerequisites).to include 'environment'
  end

  # This test fails
  it 'creates AnotherModel' do
    my_hash = {foo => 'bar'}
    allow(MyClient::Event).to receive(:list).and_return(my_hash)

    expect { task.execute }.not_to raise_error

    expect(AnotherModel.count).to eq(1)
  end
end

The problem is that for some reason, executing this code results in the following error:问题是由于某种原因,执行此代码会导致以下错误:

Failure/Error: AnotherModel.count
ActiveRecord::StatementInvalid:
  PG::InFailedSqlTransaction: ERROR:  current transaction is aborted, commands ignored until end of transaction block

The rake task looks like this: rake 任务如下所示:

namespace :some do
  desc 'Parse stream'
  task my_task: :environment do |_t|
    cint_events['events'].each do |event|
      begin
        events = MyClient::Event.list(some_hash)
        events.each do |event|
          if some_condition
            # The test should check whether this object gets created
            AnotherModel.first_or_create_by(foo: some_hash['foo'])
          end
        end
      rescue => e
        # Log errors
      end
    end
  end
end

I've tried running:我试过运行:

RAILS_ENV=test rake db:drop db:create db:migrate

and then running the spec again but I keep getting the aforementioned error.然后再次运行规范,但我不断收到上述错误。 What might this be caused by?这可能是什么原因造成的?

Thanks in advance!提前致谢!

You configured your tests to run in a database transaction, which is a good thing.您将测试配置为在数据库事务中运行,这是一件好事。 But within your rake task you just eat up all errors that appear with:但是在你的 rake 任务中,你只会吃掉所有出现的错误:

rescue => e
  # Log errors
end

However, certain errors may still cause you transaction to fail and rollback.但是,某些错误可能仍会导致您的事务失败和回滚。 So my guess is, that some severe error is happening the first time you do a call to the database (For example, the column foo is not known to the database).所以我的猜测是,第一次调用数据库时发生了一些严重的错误(例如,数据库不知道列foo )。 After that, it catches the error and you are adding a statement ( AnotherModel.count ) to the already aborted transaction, which fails.之后,它会捕获错误,并且您正在向已中止的事务添加一条语句 ( AnotherModel.count ),该事务失败了。

So a good place to start is to check what the value of e.message is in your rescue block .因此,一个好的起点是检查您的救援块中e.message的值是什么

Also note : It is never a good idea to rescue all errors blindly, and almost always leads to strange and unexpected behaviours.另请注意:盲目地挽救所有错误绝不是一个好主意,而且几乎总是会导致奇怪和意外的行为。

This error seems to occur when in a test environment and your SQL query via ActiveRecord doesn't recognize a field in your query.当在测试环境中并且通过 ActiveRecord 的 SQL 查询无法识别查询中的字段时,似乎会发生此错误。 In other words you have a scope or are trying to return some ActiveRecord relation with a bad database column name.换句话说,您有一个范围或试图返回一些带有错误数据库列名的 ActiveRecord 关系。

See this related post: ActiveRecord::StatementInvalid: PG InFailedSqlTransaction请参阅此相关帖子: ActiveRecord::StatementInvalid: PG InFailedSqlTransaction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM