Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading ActiveRecord fixtures with RSpec without Rails

I am using some ActiveRecord models outside of Rails for which I am writing unit tests. In my tests, I would like to be able to use fixtures and thought I would use some of rspec-rails features for that. I cannot simply use require "rspec-rails" because it has some Rails dependencies and I am not using Rails.

Here is the spec_helper I am using:

require 'active_record'
require 'active_record/fixtures'
require 'active_support'
require 'rspec/rails/extensions/active_record/base'
require 'rspec/rails/adapters'
require 'rspec/rails/fixture_support'  # Includes ActiveRecord::TestFixtures
                                       # into the RSpec config

require 'my_models'

# Setup database connection
environment = "test"
configuration = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.establish_connection(configuration[environment])

RSpec.configure do |config|
  config.fixture_path = File.expand_path("../../test/fixtures", __FILE__)

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = "random"

  # Run each test inside a DB transaction
  config.around(:each) do |test|
    ActiveRecord::Base.transaction do
      test.run
      raise ActiveRecord::Rollback
    end
  end
end

And here is an example of a test

require 'spec_helper'

describe Transaction do

  before :each do
    self.class.fixtures :users, :merchants
  end

  it "should do this and that" do
    ...
  end
end

The problem is that, this way, the fixtures are not loaded. I looked into the rspec-rails code but cannot figure out what module I should extend or method I should call.

like image 304
Rodrigue Avatar asked Jan 25 '13 10:01

Rodrigue


1 Answers

After diving into the Active Record code, I figured that the reason why the fixtures were not loaded was because I had not set ActiveRecord::Base.configurations. The following fixed the issue:

configuration = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.configurations = configuration
like image 123
Rodrigue Avatar answered Oct 24 '22 18:10

Rodrigue