【问题标题】:Get full text content of html email in RSpec在 RSpec 中获取 html 电子邮件的全文内容
【发布时间】:2018-04-26 08:50:40
【问题描述】:

如何在 rspec 中将 html 电子邮件的全文内容作为单行字符串获取?

假设这是mail.html.haml:

%p 
  This product is worth: 
  = @amount
  So buy it now!

在 rspec 我先发送电子邮件,然后这样做:

expect(ActionMailer::Base.deliveries.last.html_part.body).to include("This product is worth: €30 So buy it now")

或:

expect(ActionMailer::Base.deliveries.last.html_part.body.raw_source).to include("This product is worth: €30 So buy it now")

或:

expect(ActionMailer::Base.deliveries.last.html_part.body.raw_source).to have_content("This product is worth: €30 So buy it now")

这些不起作用,因为 html 像这样输出到 rspec:

 + This product is worth:
 + €30
 + So buy it now!

所以我的原始代码是正确的,但我似乎无法在 rspec 中获取它。如何将这 3 行合并为 1 行,以便正确调用 include 或 have_content?

*编辑

Failure/Error:
       expect(ActionMailer::Base.deliveries.last.html_part.body.raw_source).to have_content(%q|This product is worth:
                                                                                               €30
                                                                                               So buy it now!|)

       expected        
       <p>
       This product is worth:
       €30
       So buy it now!
       Good luck!
       </p>

【问题讨论】:

  • "This product is worth: €30 So buy it now"改成"This product is worth:\n€30\nSo buy it now"?
  • 感谢您的帮助,但实际上我正在寻找一种方法来做到这一点,而无需在我的字符串中添加额外的转义,因为如果您有大量文本也碰巧发生了变化,那么它会变得难以阅读/维护有时。
  • 添加了另一种选择作为答案。检查这是否有帮助
  • 顺便说一句:在这种情况下,使用“此产品价值:\n€30\n所以现在购买”也不起作用。
  • 因为它也期望包含

    标记,这不是您所期望的?

标签: ruby-on-rails ruby ruby-on-rails-4 rspec rspec-rails


【解决方案1】:

怎么样:

expect(ActionMailer::Base.deliveries.last.html_part.body.raw_source).to have_content(
%q|This product is worth:
€30
So buy it now|)

我不建议修改检索,因为从技术上讲,这会使规范变得无关紧要,因为匹配与呈现的内容并不完全相同。您可以像上面那样将其分解,这样可以避免转义内容。

如果您有很多这样的测试,您可能希望将预期结果保存在某些数据存储(db/factory/yaml 等)中并与它们进行比较。

【讨论】:

  • 这似乎以与 RSpec 在终端中输出电子邮件相同的方式拆分文本,但测试仍然失败,所以我猜它不是那样读取的。
  • 你能发布它的预期和得到的结果 - 你在规范失败中得到的结果
  • 将失败添加到 OP
【解决方案2】:

答案很简单。 HAML 需要像这样内联:

%p This product is worth: #{@amount} So buy it now!

或者变量需要像这样插值:

%p 
  This product is worth: 
  #{@amount}
  So buy it now!

【讨论】:

    猜你喜欢
    • 2013-04-05
    • 1970-01-01
    • 2012-05-29
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    相关资源
    最近更新 更多