Tuesday, June 30, 2009

Using The Rails Console for Controller Testing

Based 100% on the information here (especially the comments), I've managed to get inside my controllers using the Rails console. This is particularly nice if you are too impatient to write unit tests.

Here's the code

require "app/models/store" # you have to require your models, though they're visible to the console itself... it's for the controllers
require "app/models/dude"
app.get("/test_one") # app.controller will then be your Controller (yeah!), and you get a new request and a new response object to use later
app.request.parameters[:what]="who?" # just showing that you can change the request... it's a RackRequest, could be a RackMockRequest or a TestRequest.... not sure what the difference would be
app.controller.process(app.request, app.response) # run the action method
app.controller.params # get at the request params
app.controller.session # get at all session vars

2 comments:

Dan Rosenstark said...

Note: this post (http://tagaholic.me/2009/06/19/page-irb-output-and-improve-ri-with-hirb.html) has the make on a better irb. To use it with rails just do require "hirb" and then Hirb.enable.

Dan Rosenstark said...

How do you get into the instance vars? Easy:

app.controller.instance_eval { @thingers }