Recipe 7.6. Interactively Testing Controllers from the Rails Console


Problem

You want to test the behavior of your application's controllers in real time, from the Rails console.

Solution

Start up a Rails console session with the ./script/console command from your application root. Use any of the methods of ActionController::Integration::Session to test your application from within the console session:

$ ruby script/console  Loading development environment. >> app.get "/reports/show_sales" => 302 >> app.response.redirect_url => "http://www.example.com/login" >> app.flash => {:notice=>"You must be logged in to view reports."} >> app.post "/login", :user => {"username"=>"admin", "password"=>"pass"} => 302 >> app.response.redirect_url => "http://www.example.com/reports/show_sales"

Discussion

By calling methods of the global app instance, you can test just as you would in your integration tests, but in real time. All methods available to integration tests are available to the app object in the console. By passing any nonfalse value to the application, you can create unique instances of ActionController::Integration::Session and assign them to variables. For example, the following assignments create two session objects (notice the unique memory addresses for each):

>> sess_one = app(true) => #<ActionController::Integration::Session:0x40a95e88 @https=false, ... >> sess_two = app(true) => #<ActionController::Integration::Session:0x40a921c0 @https=false, ...

The new_session method does the same thing as app(true) but takes an optional code block that can be used to further initialize the session. Here's how to create a new session instance that mimics the behavior of an HTTPS session:

>> sess_three = new_session { |s| s.https! } => #<ActionController::Integration::Session:0x40a6dc44 @https=true, ...

For added feedback, you can enter commands in the console session while watching the output of ./script/server in another window. The following is the resultant output of invoking the app.get "/reports/show_sales" method from the console:

Processing ReportsController#show_sales       (for 127.0.0.1 at 2006-04-15 17:46:26) [GET]   Session ID: 9dd6a4e3c591c484a243d166f123fd10   Parameters: {"action"=>"show_sales", "controller"=>"reports"} Redirected to https://www.example.com/login Completed in 0.00160 (624 reqs/sec) |       302 Found [https://www.example.com/reports/show_sales]

Assertions may be called from the console session objects but the output is a little different from what you may be used to. An assertion that doesn't fail returns nil, while those that do fail raise the appropriate Test::Unit::AssertionFailedError.

See Also

  • Section 3.5"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net