Search code examples
localerspec-rails

Rails rspec view with locale, No route matches


This spec passes but fails after introducing locale (the application however works):

require 'spec_helper'
describe "products/show" do
  before do
    assign(:product, mock_model("Product", name: "Car", description: "petrol engine"))
  end
  it "renders name" do
    render
    expect(rendered).to match /Car/
  end
end

Then I add a scope to the routes to include the locale: ...

  scope "/:locale" do
    resources :products
    root :to => 'products#index'
  end

...

In application controller I define:

def self.default_url_options(options={})
    logger.debug "default_url_options is passed options: #{options.inspect}\n"
    I18n.locale = 'en'  # fixed for tests
    { :locale => I18n.locale}
end

In the browser the app works again with paths like /en/product/1 to render the show template

But my test above fails with:

1) products/show renders name Failure/Error: render ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"products", :locale=>#} # ./app/views/products/show.html.erb:14:in _app_views_products_show_html_erb__333746538_80999240' # ./spec/views/products/show.html.erb_spec.rb:10:inblock (2 levels) in '

Why does the test fail while the app works?

How do I make it pass?


Solution

  • This solution works for me:

    copied from https://github.com/rspec/rspec-rails/issues/255 author: https://github.com/oelmekki

    class ActionDispatch::Routing::RouteSet
      def url_for_with_locale_fix(options)
        url_for_without_locale_fix({:locale => I18n.default_locale}.merge(options))
      end
      alias_method_chain :url_for, :locale_fix
    end