Ruby on rails Rspec-为正确生成的电子邮件寻址
我只想测试用户电子邮件,因此我有以下内容:Ruby on rails Rspec-为正确生成的电子邮件寻址,ruby-on-rails,ruby,testing,rspec,Ruby On Rails,Ruby,Testing,Rspec,我只想测试用户电子邮件,因此我有以下内容: 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 更新 如您所见,我正在使用序列生成电子邮件,因此现在我想测试我是否指向用户的
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
更新
如您所见,我正在使用序列生成电子邮件,因此现在我想测试我是否指向用户的正确电子邮件地址,例如,我想从控制器向正确的用户发送电子邮件:
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>>]
1)用户控制器管理用户应通知用户其配置文件
失败/错误:ActionMailer::Base.deliveries.应包括[user.email]
预期[#]包括[”user15@example.com"]
差异:
@@ -1,2 +1,2 @@
-[["user15@example.com"]]
+[#]
有什么帮助吗?tnx.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:将所有的放到一个数组中,以便于比较
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
你能展示更多的背景吗?您实际将电子邮件分配给用户的位置?我认为目标不是测试工厂…分配
仅在控制器中有意义。你只展示了一个完全没有上下文的示例,如何调试?我更新了我的问题,为你提供了更多的细节。你知道“user.email指向不同的电子邮件地址”吗?它不像出厂时会失败。你能在匹配行之前包含上一次出现的user.email
?我需要知道您将其与什么进行比较。因此,如果您在执行此操作时发送多封电子邮件,则此方法将失败,最后一封电子邮件将不指向您希望发送的电子邮件地址。@STD,您刚刚创建了一个用户,如何发送多封电子邮件?即使有多封电子邮件,也有办法,但在这种情况下不行。我之所以使用include
,是因为我要处理多封电子邮件。我更新了问题,请看一看。谢谢,看起来不错;但是问题仍然存在,因为user.email
指向不同的电子邮件;请看一下上面的rspec
错误。@stsd,你看到我的“另一个注释”了吗?
# Remove this line
# let(:user) { FactoryGirl.create(:user) }
@user = FactoryGirl.create(:user)
expect(emails).to include(@user.email)