我的Ruby on Rails web应用程序向客户发送了一封欢迎电子邮件,我想要编写一个测试,以确保该电子邮件包含一个标签,其中src是一个.png文件。我看到assert_select可能会做我想做的事情,但是因为我的电子邮件是一个Mail::Message
类,所以我只能从电子邮件中获取html。提前感谢您的帮助!
发布于 2018-07-06 04:06:32
下面是来自模范红矿的assert_select_email
:
assert_select_email do
assert_select 'a[href^=?]', 'http://localhost:3000/settings'
end
所有的Rails程序员都应该学习像Redmine这样的文献来学习很多有用的技巧。
# Extracts the body of an email and runs nested assertions on it.
#
# You must enable deliveries for this assertion to work, use:
# ActionMailer::Base.perform_deliveries = true
#
# assert_select_email do
# assert_select "h1", "Email alert"
# end
#
# assert_select_email do
# items = assert_select "ol>li"
# items.each do
# # Work with items here...
# end
# end
def assert_select_email(&block)
deliveries = ActionMailer::Base.deliveries
assert !deliveries.empty?, "No e-mail in delivery list"
deliveries.each do |delivery|
(delivery.parts.empty? ? [delivery] : delivery.parts).each do |part|
if part["Content-Type"].to_s =~ /^text\/html\W/
root = Nokogiri::HTML::DocumentFragment.parse(part.body.to_s)
assert_select root, ":root", &block
end
end
end
end
发布于 2018-07-06 03:51:48
我不确定它是否有效,但我猜你可以做这样的事情。
expect(mail.body).to match(/.*.<img.*.png.*/)
https://github.com/rspec/rspec-expectations#regular-expressions
https://stackoverflow.com/questions/51198546
复制相似问题