Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Rails test from deleting seed data

I am using seeds.rb to populate some State model reference data:

State.create :name => 'Alabama', :abbreviation => 'AL'
State.create :name => 'Alaska', :abbreviation => 'AK'
# ...

Although I am not using state fixtures (since it's seed data to begin with, I think it wouldn't be DRY to have to duplicate this purely for tests), the Rails testing framework seems to delete all the State seed data during testing. (I am dropping, recreating, migrating and reseeding the test db, and confirmed the data is there prior to a unit test running.)

The result is this assertion succeeding in seeds.rb but failing in a one-line test:

assert_equal 51, State.all.size

1) Failure:
test_state_seeds_are_present(StateTest) [/test/unit/state_test.rb:24]:
<51> expected but was
<0>.
1 tests, 1 assertions, 1 failures, 0 errors

I have tried both explicitly listing non-State models in the base test class fixtures statement, as well as flipping the transactional fixtures flag (as expected, this only affects records created during the test). Naturally the test under consideration is not itself deleting these records.

The State records are always deleted. Is there a way to tell Rails to just get its hands off the seed data? Do I need to duplicate all the data in fixtures to make sure it gets re-loaded? Short of a major political event, I would expect the state data to be relatively stable.

tia

like image 566
aaron Avatar asked Dec 14 '09 03:12

aaron


2 Answers

Tests delete all the data from the database and then load your fixtures (if you have any).

You need to get your test helper to load the seed file before the tests run. There are a couple ways to do that, check out my similar question: How to load db:seed data into test database automatically?

The easiest way is probably just to add

require "#{Rails.root}/db/seeds.rb"

to the top of your test_helper.rb file (assuming you use the built-in testing framework).

like image 114
Luke Francl Avatar answered Nov 12 '22 21:11

Luke Francl


The "seed" feature is not integrated into the test architecture. Tests are built around fixtures and each time you run the test suite, Rails loads the data from the fixtures and replaces the existing content.

However, having the database populated with your seed data is really straightforward.

In your test_helper.rb file add a new setup method in the base ActionSupport::TestCase class.

class ActionSupport::TestCase < ...

  setup :load_seeds

  protected 

    def load_seeds
      load "#{Rails.root}/db/seeds.rb"
    end

end
like image 4
Simone Carletti Avatar answered Nov 12 '22 22:11

Simone Carletti