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 :)
May be late... Rails 4
So I had a similar but slightly different need. I wanted to use my existing fixtures (from my rspec test) to populate my development database. This is how I did it by adding a new task to my rake file (located in libs/tasks/*.rake):
If you combine this with a db:reset you can populate your development environment at will by adding this to your rake task as well:
Then you can call rake db:reseed to populate from fixture YAML files.
You can load a fixture in the Rails 3.2 console as follows:
You can load fixtures into your development database too:
You should be able to load your fixtures prior to entering console. Like this:
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:
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:
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'.
It's possible to specify an alternate fixture directory using the FIXTURES_DIR variable. The value should be relative to test/fixtures.
It's also possible to specify a limited set of fixtures