5
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 ?

3
  • 1
    Is there a namespace, convention, or tag that you plan on applying to distinguish those routes that you need a default parameter on? That could impact strategy used. Commented Aug 5, 2021 at 12:27
  • 1
    @stringsn88keys , yes: for clarity I simplified the routes, but all localized routes are in the same 'dashboard` namespace, so it's actually domain.com/en/dashboard/courses for instance
    – gfd
    Commented Aug 5, 2021 at 13:31
  • how about stub default_url_options to return { locale: locale_you_want} on test cases which will be test for some routes , so it's only effected on those test cases.
    – Lam Phan
    Commented Aug 5, 2021 at 14:12

1 Answer 1

1

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
2
  • Thanks for the idea, but the problem occurs even before that: when trying to generate the course_path(@course) in the visit line of the spec, it needs the locale then...
    – gfd
    Commented Aug 5, 2021 at 13:35
  • This is still present in Rails 7.1 and unclear how to set up correctly. It seems to me that the underlying problem sits on the border of RSpec and Rails and neither side documents the interplay very nice.
    – Felix
    Commented Feb 29 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.