7

rspec と国際化をテストする方法がわかりません。たとえば、私が行うリクエストテストでは

I18n.available_locales.each do |locale|
  visit users_path(locale: locale)
  #...
end

すべてのロケールテストが正しく動作します。

しかしメーラーでは、このトリックは機能しません。

user_mailer_spec.rb

require "spec_helper"

describe UserMailer do
  I18n.available_locales.each do |locale|
    let(:user) { FactoryGirl.build(:user, locale: locale.to_s) }
    let(:mail_registration) { UserMailer.registration_confirmation(user) }

    it "should send registration confirmation" do
      puts locale.to_yaml
      mail_registration.body.encoded.should include("test") # it will return error with text which allow me to ensure that for each locale the test call only :en locale email template
    end
  end
end

数回 (私が持っているロケールと同じ数だけ) 実行しますが、毎回デフォルトのロケールに対してのみ html を生成します。

UserMailer.registration_confirmation(@user).deliverコントローラーから呼び出すと、正常に動作します。

user_mailer.rb

...
def registration_confirmation(user)
  @user = user
  mail(to: user.email, subject: t('user_mailer.registration_confirmation.subject')) do |format|
      format.html { render :layout => 'mailer'}
      format.text
  end
end
...

ビュー/user_mailer/registration_confirmation.text.erb

<%=t '.thx' %>, <%= @user.name %>.
<%=t '.site_description' %>
<%=t '.credentials' %>:
<%=t '.email' %>: <%= @user.email %>
<%=t '.password' %>: <%= @user.password %>
<%=t '.sign_in_text' %>: <%= signin_url %>
---
<%=t 'unsubscribe' %>

繰り返しますが、すべてのロケールで問題なく動作します。rspec テストについてのみ質問があります。

4

2 に答える 2

2

ブロックが変数describe/contextを認識できるようにするには、テストをブロックでラップする必要があると思います。itlet

require "spec_helper"

describe UserMailer do
  I18n.available_locales.each do |locale|
    describe "registration" do
      let(:user) { FactoryGirl.build(:user, locale: locale.to_s) }
      let(:mail_registration) { UserMailer.registration_confirmation(user) }

      it "should send registration confirmation" do
        puts locale.to_yaml
        mail_registration.body.encoded.should include("test")
      end
    end
    # ...
  end
  # ...
end

理由については、変数のスコープに関するこの StackOverflow の回答letが役立つ可能性があります。

編集

mailユーザーにロケールを割り当てたが、それをメソッドに渡していないという問題はありますか? おそらく、この StackOverflow の回答が参考になるでしょう。うまくいけば、そこにある2つの答えのうちの1つがあなたの状況に関連するでしょう. 最初の答えをあなたの状況に適応させる私の簡単な試みは次のとおりです(明らかにテストされていません):

user_mailer.rb

...
def registration_confirmation(user)
  @user = user
  I18n.with_locale(user.locale) do
    mail(to: user.email, 
             subject: t('user_mailer.registration_confirmation.subject')) do |format|
      format.html { render :layout => 'mailer' }
      format.text
    end
  end
end
... 
于 2012-12-19T07:47:44.217 に答える
1

次のように、おそらくロケールを指定する必要があります。

mail_subscribe.body.encoded.should include(t('user_mailer.subscribe_confirmation.stay', locale: locale))

メソッドの呼び出しのI18n.locale = user.locale直前に追加してみることもできます。mailregistration_confirmation

于 2012-12-14T09:17:46.697 に答える