在RSpec中获取html电子邮件的全文内容

时间:2018-04-26 08:50:40

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

如何在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>

2 个答案:

答案 0 :(得分:0)

怎么样:

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等)中并与它们进行比较。

答案 1 :(得分:0)

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

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

或变量需要像这样插值:

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