加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 21:10:05 所属栏目:百科 来源:网络整理
导读:我不明白如何使用rspec和国际化进行测试. 例如,在我做的请求测试中 I18n.available_locales.each do |locale| visit users_path(locale: locale) #...end 它工作得很好:每个语言环境测试都是正确的. 但在邮寄者中,这个技巧不起作用. user_mailer_spec.rb re
我不明白如何使用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
...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读