0

In my config.routes.rb file:

 scope '(:locale)' do
    resources :techniques, path: '/applications' do
      get '/complete_list' => 'techniques#complete_list'
    end
 end

In my Gemfile:

group :development, :test do
  gem 'rspec-rails'
  gem 'byebug'
  gem 'better_errors'
  gem 'factory_girl_rails'
  gem 'faker'
end

group :test do
  gem 'poltergeist'
  gem 'capybara'
  gem 'launchy'
  gem 'database_cleaner'
end

In my application_controller.rb:

  before_filter :set_locale
  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end

  def default_url_options(options = {})
    { locale: I18n.locale }.merge options
  end

In my spec:

visit techniques_path

It always flunks with:

I18n::InvalidLocale - "applications" is not a valid locale:

And it highlights this line in my application_controller:

I18n.locale = params[:locale] || I18n.default_locale

I can make things work by changing the spec to read as:

visit techniques_path(locale: :en)

But I thought that setting up the default_url_options in the application controller would take care of that automatically. What am I missing here?

croceldon
  • 4,511
  • 11
  • 57
  • 92

1 Answers1

3

When you want to test behaviour from ApplicationController, you need an so called anonymous controller, a controller that inherits from ApplicationController and is testable:

describe ApplicationController do
  controller do
    def index      
    end
  end

  describe "language setting" do    
    it "uses parameter" do
      expect(I18n).to receive(:locale=).with('en')
      get :index, locale: 'en'
    end

    it "falls back to default_locale" do
      I18n.default_locale = 'nl'
      expect(I18n).to receive(:locale=).with('nl')
      get :index
    end
  end
end

Edit: I now see you need to add the locales param to the feature-tests.

When you want to pass parameters into a path, just add them as hash:

 visit techniques_path({locale: 'en'})

However, I find it bad practice to use url_helpers in the feature-tests. I am assuming the "visit" is feature/integration-test, since I have not seen it used elsewhere. Instead, when testing the pure integration, use actual strings as paths:

 visit '/en/techniques/1234'
 visit "/en/techniques/@technique.id"

This a.o. communicates that the feature tests are a separate application: one that does not rely on internal state of the app. As if it were a "user" using a browser clicking through the app. A user, using firefox, cannot use "technique_path", he can only click on links, or type a URL into the browser bar.

berkes
  • 26,996
  • 27
  • 115
  • 206