Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load and use fixture in rails console

I wonder if there's a way to load and/or use fixture in rails console. Actually, I'd like to create a user from my fixture users.yml to do some testing without having to go through all the "pain" of doing User.new(:name = "John", :email = "..") each time.
I am currently in test environment (rails c RAILS_ENV=test).

If it's not a good way to do things, please say it. I'm new to Rails so I'm here to learn :)

like image 559
Patrick Pruneau Avatar asked Aug 12 '11 17:08

Patrick Pruneau


2 Answers

You should be able to load your fixtures prior to entering console. Like this:

RAILS_ENV=test bin/rails db:fixtures:load RAILS_ENV=test bin/rails console 

However, you still won't be able to access your fixture data like you would in a test. This simply loads your test database with your fixtures data. So you'd still have to do something like:

user = User.find_by(name: "John") 

But, you can still create shortcuts for this sort of thing. You can add any ruby code you'd like to your ~/.irbrc. I suggest creating a .railsrc file as described here. You can then set up things like:

john = User.find_by(name: "John") 

So now you can just start referring to the variable 'john' after console loads. Incidentally, the post I linked to shows how to set up a global .railsrc file, but you could set it up so that you had a per project .railsrc. Or, if you want something a little less fancy, but easy to do... just create a ruby file in your project (maybe 'shortcuts.rb'). After console is loaded, just do a require 'shortcuts'.

like image 171
Ryan Sandridge Avatar answered Oct 04 '22 15:10

Ryan Sandridge


May be late... Rails 4

require 'active_record/fixtures' ActiveRecord::FixtureSet.create_fixtures(Rails.root.join('test', 'fixtures'), 'users') 
like image 36
woto Avatar answered Oct 04 '22 14:10

woto