我只是想测试用户的电子邮件,所以我有这个:
FactoryGirl.define do
factory :user do |u|
u.sequence(:email) {|n| "user#{n}@example.com" }
u.first_name { Faker::Name.first_name }
u.password "foo123"
end
end
如您所见,我正在使用sequence
生成电子邮件,所以现在我想测试我是否指向用户的正确电子邮件地址,例如我想向右侧发送电子邮件来自controller
的用户:
let(:user) { FactoryGirl.create(:user) }
it "should notify user about his profile" do
@user = FactoryGirl.create(:user)
# profile update..
ActionMailer::Base.deliveries.should include [@user.email]
end
以上测试失败,因为user.email
指向不同的电子邮件地址,而不是FactoryGirl制作的电子邮件地址:
1) UserController Manage users should notify user about his profile
Failure/Error: ActionMailer::Base.deliveries.should include [user.email]
expected [#<Mail::Message:5059500, Multipart: false, Headers: <From: foo <info@foo.com>>, <To: user16@example.com>, <Message-ID: <..41d@linux.mail>>, <Subject: foo>, <Content-Type: text/html>, <Content-Transfer-Encoding: 7bit>>] to include ["user15@example.com"]
Diff:
@@ -1,2 +1,2 @@
-[["user15@example.com"]]
+[#<Mail::Message:5059500, Multipart: false, Headers: <..>, <From: foo Verticals <info@castaclip.com>>, <To: user16@example.com>, <Message-ID: <..41d@linux.mail>>, <Subject: foo>, <Content-Type: text/html>, <Content-Transfer-Encoding: 7bit>>]
任何帮助? TNX。
答案 0 :(得分:0)
ActionMailer::Base.deliveries
中包含的是邮件对象数组。您不能指望邮件元素与电子邮件匹配。那是不对的。只有邮件对象的to
方法才能与电子邮件进行比较。
你可以这样做
last_email = ActionMailer::Base.deliveries.last
expect(last_email.to).to have_content(user.email)
添加强>
OP补充说,这是针对发送给一组用户的多封电子邮件。非常合理。我建议采用以下方法:
步骤1:清除每个示例中的电子邮件
before { ActionMailer::Base.deliveries = [] }
第2步:将所有to
放入数组中以便于比较
it "will check if email is sent" do
emails = []
ActionMailer::Base.deliveries.each do |m|
emails << m.to
end
expect(emails).to include(user.email)
end
用户问题的另一个注意事项:我没有看到完整的代码。但如果您遇到错误用户的问题,使用实例变量而不是let
来定义工厂会更安全。
# Remove this line
# let(:user) { FactoryGirl.create(:user) }
@user = FactoryGirl.create(:user)
expect(emails).to include(@user.email)