201 words — 1 minutes read

assert_select and url_for

In the Extreme Testing presentation, I have a slide with assert_select examples, some of them lifted from the assert_select cheat sheet. All fine and dandy, except that this

assert_select "form[action=?]", url_for( :action => 'foo' )

just doesn’t work. url_for is a method of the controller, not the ControllerTest class.

So in order to overcome that limitation, you’d need to

    assert_select "form[action=?]", @controller.url_for( :action => 'foo' )

which doesn’t throw an error, but doesn’t work either, because url_for insists on adding https://test.host/ to the generated URL. Of course, that’s not what’s in the form you have generated. What you need to do, is to add the parameter :only_path => true to the url_for call:

    assert_select "form[action=?]", @controller.url_for( :action => 'foo', : only_path  => true )

which – finally – works, but is very unwieldy.

Luckily, we are working in Ruby, not any other language. Drop this

class << self
  def url_for(options, *parameters_for_method_reference)
    options.merge! : only_path => true 
    @controller.url_for(options,  *parameters_for_method_reference)

into the setup method in your functional test, and your set to use:

assert_select "form[action=?]", url_for( :action => 'foo' )
assert_select "a[href=?]", url_for( :controller => 'foo', :action => 'bar', :id => @baz) 

as you intended.

Technorati Tags: rails, ruby, rubyonrails, testing

Jens-Christian Fischer

Maker. Musician