在我的config.routes.rb
文件中:
scope '(:locale)' do
resources :techniques, path: '/applications' do
get '/complete_list' => 'techniques#complete_list'
end
end
在我的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
在我的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
在我的规范中:
visit techniques_path
总是有些不满:
I18n::InvalidLocale - "applications" is not a valid locale:
它在我的application_controller中强调了这一行:
I18n.locale = params[:locale] || I18n.default_locale
我可以通过将规范更改为:
来使事情有效visit techniques_path(locale: :en)
但我认为在应用程序控制器中设置default_url_options会自动处理。我在这里缺少什么?
答案 0 :(得分:1)
当您想要从ApplicationController
测试行为时,您需要一个所谓的匿名控制器,一个继承自ApplicationController
并且可以测试的控制器:
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
编辑:我现在看到你需要将locales参数添加到功能测试中。
如果要将参数传递到路径中,只需将它们添加为哈希:
visit techniques_path({locale: 'en'})
但是,我发现在功能测试中使用url_helpers是不好的做法。我假设"访问"是功能/集成测试,因为我还没有看到它在其他地方使用过。 相反,在测试纯集成时,请使用实际字符串作为路径:
visit '/en/techniques/1234'
visit "/en/techniques/@technique.id"
这个a.o.传达功能测试是一个单独的应用程序:一个不依赖于应用程序的内部状态的应用程序。好像它是一个"用户"使用浏览器点击应用程序。使用firefox的用户不能使用" technique_path",他只能点击链接,或在浏览器栏中输入URL。