Вопрос

My Ruby version is ruby 1.9.3p385 . My Rails version is 3.2.12.

I use the following to load the test database:

rake db:seed RAILS_ENV=test

Everything works great. All the Factory Girl stuff is loaded nicely.

Contents of test/factories.rb contains the factories. The contents of db/seeds.rb is simply:

FactoryGirl.create(:music_categorization)
FactoryGirl.create(:dance_categorization)

Now, when I run the tests using the following command:

rake test

Rails deletes all the seed data and the tests fail. I'd like a way to prevent "rake test" from deleting data.

The other route I went was to load the seed data as part of the "rake test" command as mentioned in this question. However, what that ends up doing is loading the test data twice (basically db/seeds.rb is called twice for some reason). I abandoned that route and now simply want to do the following to run my tests:

rake db:seed RAILS_ENV=test
rake test

Any help is appreciated. I basically want to prevent rake test from deleting my data OR figure out a way to not have db/seeds.rb called twice.

Это было полезно?

Решение

AFAIK its not usual to use db:seed to load data for your tests, its normally just used to load seed data for development purposes only.

Instead you should create test data in the actual test file. Usually test data is deleted after each test using something like database_cleaner, so each test starts with an empty database.

For example in rspec you can load test data in a let block, before block or in the test itself, e.g

require 'spec_helper'

describe Page do
  let(:user) { FactoryGirl.create(:user) }

   before do
     # create some data
   end

  it '#name returns XYZ' do
    page = FactoryGirl.create(:page, :user => user)
    page.description.should == 'XYZ'
  end

  it '#description returns ABC' do
    page = FactoryGirl.create(:page, :user => user)
    page.description.should == 'ABC'
  end
end

Другие советы

First, let me just say that in general you should not be using seed data in your tests. Tests are supposed to run with an empty database, and you create only the data you need for each test.

In your case, you seem to have not understood the meaning of the seed data, which is basically core data that your application needs to work properly. If you need to instantiate a couple of models in your tests, simply do (assuming you're using rspec)

    before(:each) do
      FactoryGirl.create(:music_categorization)
      FactoryGirl.create(:dance_categorization)
    end

If you still want to run the tests with the seed data, you can always try and run rspec, which will just run all you rspec examples leaving the test database as is. But believe, that's not what you want.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top