gpt4 book ai didi

ruby-on-rails - 带有 I18n 的邮件程序的 Rspec

转载 作者:行者123 更新时间:2023-12-04 12:42:01 25 4
gpt4 key购买 nike

我不明白如何使用 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从 Controller ,它工作正常。

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 中阻止以允许 it阻止查看您的 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可能有帮助。

编辑

问题是您为用户分配了语言环境,但没有将其传递给 mail方法在哪里?也许 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
...

关于ruby-on-rails - 带有 I18n 的邮件程序的 Rspec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13875329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com