Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ActionView::TestCase does not honor default_url_options set in application_controller.rb

#5998

Using Rails 3, I have a :scope in routes.rb:

scope "(/:locale)" do
  resources :products
end

In application_controller.rb I set the default :locale

def default_url_options(options={})
  {:locale => "en-US"}
end

In my views, this works when I test in my browser, but ActionView::TestCase tests fail

<%= link_to product.name, product %>

While running a test, I see:

No route matches {:action=>"show", :controller=>"products", :locale=>#<Product id: ...>}

Here is a test that fails:

class ProductShowTest < ActionView::TestCase
  def test_render
    render "products/show", :product => Product.new(:name => "WidgetA")
    assert_match /WidgetA/, rendered
  end
end

Reported by AdamTao · November 17th, 2010 @ 10:33 PM

State: invalid
Milestone: 3.0.5
Assigned to: Andrew White Andrew White
Importance: Low

Activity

  1. Andrew White
    Andrew White
    • State changed from new to open
    • Milestone cleared.
    • Assigned user set to Andrew White
    • Importance changed from to Low

    November 18th, 2010 @ 07:06 AM

  2. Santiago Pastorino
  3. Andrew White
    Andrew White
    • State changed from open to invalid

    When unit testing views the controller is just a stub controller which inherits from ActionController::Base and not ApplicationController. You need to override this stub if you need special behaviour like default_url_options, e.g:

    # app/views/products/index.html.erb
    <%= link_to('Products', products_path) %>
    
    # test/unit/views/products_index_test.rb
    require 'test_helper'
    
    class ProductsIndexTest < ActionView::TestCase
      class ProductsController < TestController
        def default_url_options
          { :locale => 'de' }
        end
      end
    
      def setup
        @controller = ProductsController.new
      end
    
      def test_render
        render :template => "products/index"
        assert_match %r{href="/de/products"}, rendered
      end
    end
    

    Note that you have to define the controller in your test as using the real one will not have a test request and response.

    February 14th, 2011 @ 10:06 AM