简体   繁体   中英

What's the best method for creating “test” database content in >= Rails 3.2.0?

I want to be able to create a few dozen users, articles (or whatever resources are unique to the app), etc to see how the app looks and responds when full. This is just for testing/dev purposes, so I want to be able to roll it back, destroy it, or whatever easily. Perhaps I'm overthinking it, who knows.

I've seen people recommend just using a standard migration, which is one idea, but I want to do this OPTIONALLY, I don't want everyone on the project to get the sample content as they update the app.

Other people have mentioned Factory Girl, but that looks like it might be either overkill or a side-use of a gem really designed for testing, etc. It wasn't perfectly clear.

So what do you all do in this case?

I recommend a rake task. You can stick it in lib/tasks and so everyone in the project gets it, but not everyone needs to run it, and only when it's run will it do anything. This a great tutorial on writing rake tasks, just remember to read the part under the Rails heading in order to learn how to bring in your models.

After that, your rake tasks is basically just ruby code. I'd suggest using the dynamic find_or_create_by methods in order to explicitly create the models you want, and if it's run multiple times, they won't be created multiple times. You can also choose to destroy all records in a particular model before creating them.

I wouldn't recommend using Factory Girl because you probably want explicit control over how your models are created.

Here's an example rake task to show how easy it is:

#lib/tasks/my_task.rake
task :fake_data => :environment do
    MyModel.find_or_create_by_name("Test")
end

Then in your console:

rake fake_data

Or:

rake fake_data RAILS_ENV=test

Ta da!

Take a look at Rails seed data features

http://railscasts.com/episodes/179-seed-data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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