1

我只想测试用户电子邮件,所以我有这个:

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。

4

1 回答 1

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)
于 2013-05-27T17:53:44.493 回答