Load and use fixture in rails console

Patrick Pruneau picture Patrick Pruneau · Aug 12, 2011 · Viewed 25.3k times · Source

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 :)

Answer

Ryan Sandridge picture Ryan Sandridge · Oct 26, 2011

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'.