ruby-on-railsrspecrake-task

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


I am currently trying to test a rake task with RSpec. My Rails version is 4.2.4 and rspec-rails version is 3.3.2.

I've have the following in 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:

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

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:

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!


Solution

  • 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:

    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). After that, it catches the error and you are adding a statement (AnotherModel.count) to the already aborted transaction, which fails.

    So a good place to start is to check what the value of e.message is in your rescue block.

    Also note: It is never a good idea to rescue all errors blindly, and almost always leads to strange and unexpected behaviours.