Skip to content

Instantly share code, notes, and snippets.

@ubugnu
Last active August 5, 2018 17:02
Show Gist options
  • Save ubugnu/1a57103b90c32991f4e512d47d9e1561 to your computer and use it in GitHub Desktop.
Save ubugnu/1a57103b90c32991f4e512d47d9e1561 to your computer and use it in GitHub Desktop.
RSpec: set locales so routes helpers do not fail in tests
# spec/support/locales.rb
RSpec.configure do |config|
# this filter hook set the default locale for the filtered examples to get
# the correct path helpers
# for example the route:
# scope "(:locale)" do
# get "xxx/:id", to: "xxx#show", as: :xxx
# end
# the helper for this route is for example:
# xxx_path(1)
# this helper will work in rails app in other than test envs, but not in test
# mode, because "1" will be assigned to :locale and not to :id, and it will
# complain from not having :id set
# the only solution I found is to stub ActionController::Base.default_url_options
config.before :example, :set_lang do |ex|
m = ex.metadata
allow(ActionController::Base).to receive(:default_url_options) \
.and_return({locale: m[:set_lang]})
end
end
# config/routes.rb
Rails.application.routes.draw do
scope "(:locale)" do
get 'view/:id', to: 'controller#action', as: :my_view
end
end
# app/views/test/_test.html.erb
"""
<% if @named_id %>
<%= my_view_path(id: 1) %>
<% else %>
<%= my_view_path(1) %>
<% end %>
"""
# spec/views/test/_test_spec.rb
require 'rails_helper'
RSpec.describe "My View" do
context 'without :locale filter hook' do
it 'raises an exception if :id is not passed as named param' do
expect {
render 'test/test'
}.to raise_error(ActionView::Template::Error, /missing required keys: \[:id\]/)
end
it 'gives /view/1 if :id is passed as named parameter' do
assign :named_id, true
render 'test/test'
expect(rendered).to match '/view/1'
end
end
context 'with :locale filter hook' do
it 'gives /en/view/1 even if :id is not passed as named parameter', set_lang: :en do
render 'test/test'
expect(rendered).to match '/en/view/1'
end
end
end
# will output
# My View
# without :locale filter hook
# gives /view/1 if :id is passed as named parameter
# raises an exception if :id is not passed as named param
# with :locale filter hook
# gives /en/view/1 even if :id is not passed as named parameter
#
# 3 examples, 0 failures
@ubugnu
Copy link
Author

ubugnu commented Aug 5, 2018

Tracking visits ...
Analytics

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment