respond_to order is important
This is the test I wrote. You’ll notice it is almost verbatim the scaffolded test.
1 2 3 4 5 6 7 8 9 10 |
def test_create num_blog_accounts = BlogAccount.count post :new, :blog_account => {:feed_url => 'http://bladibla.com/'}, :commit => 'Close' assert_redirected_to blog_accounts_url assert_equal num_blog_accounts + 1, BlogAccount.count end |
Interestingly, I made it fail with the following simple code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
def new return edit unless params[:id].blank? @title = 'Creating blog account' @blog_account = BlogAccount.new save_and_navigate if request.post? end protected def save_and_navigate if @blog_account.update_attributes(params[:blog_account]) flash_success 'BlogAccount was successfully updated.' respond_to do |wants| wants.js do render :action => 'save', :content_type => 'text/javascript; charset=utf-8', :layout => false end wants.html do redirect_to blog_accounts_url end end end end |
1 2 3 4 5 6 7 8 9 10 11 |
$ ruby test\functional\admin\blog_accounts_controller_test.rb -n test_create Loaded suite test/functional/admin/blog_accounts_controller_test Started F Finished in 0.188 seconds. 1) Failure: test_create(Admin::BlogAccountsControllerTest) [test/functional/admin/blog_accounts_controller_test.rb:42]: Expected response to be a <:redirect>, but was <200> 1 tests, 1 assertions, 1 failures, 0 errors |
respond_to block did the trick:
1 2 3 4 5 6 7 8 |
respond_to do |wants| wants.html do redirect_to blog_accounts_url end wants.js do render :action => 'save', :content_type => 'text/javascript; charset=utf-8', :layout => false end end |
This is partially logical. Of course, the request doesn’t have an Accept header, so Rails uses the default, which is to return in order the order of definition.
Alternatively, setting the request’s Accept header would do the trick:
1 2 3 4 5 6 7 |
def setup @controller = Admin::BlogAccountsController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @request.env['HTTP_ACCEPT'] = 'text/html' end |