ruby-on-rails – 用于I18n邮件的Rspec

我不明白如何使用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测试的问题.

解决方法

我想你可能必须将你的测试包装在一个describe / context块中,以允许它阻塞看到你的let变量:
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

至于为什么,也许this StackOverflow answer on let variable scoping可能有所帮助.

编辑

是您为用户分配了区域设置的问题,但是您没有在任何地方将其传递给邮件方法?也许this StackOverflow answer可以参考.希望这两个答案中的一个与您的情况相关.这是我根据您的情况调整第一个答案的简单尝试(显然未经测试):

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
...

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...