Improving Wetware

Because technology is never the issue

Ruby on Rails Gotcha — cannot always omit parenthesis on a method call

Posted by Pete McBreen Thu, 03 Feb 2011 18:45:00 GMT

When trying to test out some legacy routes I got a really obtuse error from rake while running the following test case

  test "legacy routing OK" do
      assert_recognizes {:controller => 'index', :action => 'contact'},  '/contact.html'
  end

All I was trying to do was make sure that any URLs saved in search engines from the old static site still worked in the new Rails based site, so no issue, just use assert_recognizes and that will make sure the routes are protected by test cases. It is not possible to use assert_routing since I did not want the new code to generate the .html style URLs. Anyway, this is what rake complained about

/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:147:in 
   `load_without_new_constant_marking': ./test/functional/index_controller_test.rb:25: 
            syntax error, unexpected tASSOC, expecting '}' (SyntaxError)
          assert_recognizes {:controller => 'index', :action => 'contact'},  '/contact.html'

         ./test/functional/index_controller_test.rb:25: syntax error, unexpected ',', expecting '}'
            assert_recognizes {:controller => 'index', :action => 'contact'},  '/contact.html'

It turns out that although the code documentation uses the normal rails convention of omitting the () around the method arguments, you cannot do that if the first parameter to a method is a hash. So the fix is to put in the parenthesis and the test runs as expected.

  test "legacy routing OK" do
      assert_recognizes( {:controller => 'index', :action => 'contact'},  '/contact.html' )
  end