Set default parameter to some rspec requests

Viewed 207
Context:

Some of our rails routes need a locale to generate url (for instance domain.com/en/courses) while the base controller (for domain.com) doesn't use locale. We set it up by adding the locale in the default_url_options of the right controller.

Problem:

But when testing it in Rspec, I get a missing required keys error asking for the locale. When I add a locale param in the spec like so visit course_path(@course, locale: :en) everything is back to normal... but we have a LOT of specs !

First attempts:

I tried using the default_url_option method in ActionView::TestCase::TestController and ActionDispatch::Routing::RouteSet like so

class ActionView::TestCase::TestController
  def default_url_options(options = {})
    { locale: I18n.default_locale }
  end
end

class ActionDispatch::Routing::RouteSet
  def default_url_options(options = {})
    { locale: I18n.default_locale }
  end
end

But it set the locale for the whole app, not just some specific routes...

Question:

Is there a way to set a default parameter for some routes in rspec support ?

1 Answers

First solution

on ApplicationController

if Rails.env.test?
  before_action :set_default_locale

  private
  def set_default_locale
    I18n.locale = params.fetch(:locale, :en)
  end
end

i know that it's not the correct way

it doesn't update your app on rspec level, but so far this is what I can think on my head


Second alternative solution

Update on route level

if Rails.env.test?
  defaults = { locale: :en }
else
  defaults = {}
end
scope "(:locale)", :locale => /en|id/, :defaults => defaults do
Related