This is the test I wrote. You’ll notice it is almost verbatim the scaffolded test.

 1 def test_create
 2   num_blog_accounts = BlogAccount.count
 3 
 4   post :new,
 5     :blog_account => {:feed_url => 'http://bladibla.com/'},
 6     :commit => 'Close'
 7   assert_redirected_to blog_accounts_url
 8 
 9   assert_equal num_blog_accounts + 1, BlogAccount.count
10 end

Interestingly, I made it fail with the following simple code:

 1 def new
 2   return edit unless params[:id].blank?
 3   @title = 'Creating blog account'
 4   @blog_account = BlogAccount.new
 5   save_and_navigate if request.post?
 6 end
 7 
 8 protected
 9 def save_and_navigate
10   if @blog_account.update_attributes(params[:blog_account])
11     flash_success 'BlogAccount was successfully updated.'
12     respond_to do |wants|
13       wants.js do
14         render :action => 'save', :content_type => 'text/javascript; charset=utf-8', :layout => false
15       end
16       wants.html do
17         redirect_to blog_accounts_url
18       end
19     end
20   end
21 end

The failure was:

 1 $ ruby test\functional\admin\blog_accounts_controller_test.rb -n test_create
 2 Loaded suite test/functional/admin/blog_accounts_controller_test
 3 Started
 4 F
 5 Finished in 0.188 seconds.
 6 
 7   1) Failure:
 8 test_create(Admin::BlogAccountsControllerTest) [test/functional/admin/blog_accounts_controller_test.rb:42]:
 9 Expected response to be a <:redirect>, but was <200>
10 
11 1 tests, 1 assertions, 1 failures, 0 errors

Flipping the order of my respond_to block did the trick:

1 respond_to do |wants|
2   wants.html do
3     redirect_to blog_accounts_url
4   end
5   wants.js do
6     render :action => 'save', :content_type => 'text/javascript; charset=utf-8', :layout => false
7   end
8 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 def setup
2   @controller = Admin::BlogAccountsController.new
3   @request    = ActionController::TestRequest.new
4   @response   = ActionController::TestResponse.new
5 
6   @request.env['HTTP_ACCEPT'] = 'text/html'
7 end

Search

Your Host

A picture of me

I am François Beausoleil, a Ruby on Rails and Scala developer. During the day, I work on Seevibes, a platform to measure social interactions related to TV shows. At night, I am interested many things. Read my biography.

Top Tags

Books I read and recommend

Links

Projects I work on

Projects I worked on