简体   繁体   English

Rails 中由 around_action 设置的测试条件

[英]Testing conditions set by around_action in Rails

In a Rails app the current locale ist set in ApplicationController through a around_action callback.在 Rails 应用程序中,当前语言环境通过around_action回调在ApplicationController设置。 This is a cleaner solution than using only a before_action which would leave the request specific locale hanging around.与仅使用before_action相比,这是一种更清洁的解决方案,后者会使请求特定的语言环境悬而未决。

class ApplicationController < ActionController::Base
  around_action :with_locale

  def with_locale
    I18n.with_locale(find_current_locale) { yield }
  end
end

Since the current locale is reset after the request finished its not so easy to access the request specific locale in a test.由于在请求完成后重置当前区域设置,因此在测试中访问请求特定区域设置并不容易。 With a before_filter the following test would pass:使用before_filter可以通过以下测试:

it 'sets locale from request'
  get :action, locale: locale
  I18n.locale.should == locale
end

I cannot think of a way to implement this test to work with an around_filter without injecting some additional logic into the controller.我想不出一种方法来实现这个测试以使用around_filter而不将一些额外的逻辑注入控制器。 Is there a simpler way with RSpec? RSpec 有更简单的方法吗?

How about checking if I18n.with_locale has been called with proper parameters.如何检查I18n.with_locale是否已使用正确的参数调用。

it 'sets locale from request'
  allow(I18n).to receive(:with_locale)
  get :action, locale: locale
  expect(I18n).to have_received(:with_locale).with(locale)   
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM