我遇到过一些工具,它们可以更容易地测试Rails应用程序中生成的电子邮件,但它们是为集成测试(即capybara-email)而设计的。但是,我正在编写一个直接与邮件程序一起工作的单元测试。
我目前有一个对我的邮件的测试,看起来像这样:
RSpec.describe DigestMailer do
describe "#daily_digest" do
let(:mail) { DigestMailer.daily_digest(user.id) }
let(:user) { create(:user) }
it "sends from the correct email" do
expect(mail.from).to eql ["support@example.com"]
end
it "renders the subject" do
expect(mail.subject).to eql "Your Daily Digest"
end
it "renders the receiver email" do
expect(mail.to).to eql [user.email]
end
it "renders the number of new posts" do
expect(mail.body.raw_source).to match "5 New Posts"
end
end
end但是,我希望能够比简单地使用正则表达式更容易地测试html内容。
我真正想做的事情是这样的:
within ".posts-section" do
expect(html_body).to have_content "5 New Posts"
expect(html_body).to have_link "View More"
expect(find_link("View More").to link_to posts_url
end我不知道是否有一种方法可以直接使用Capybara来实现这样的事情。也许有其他选择可以提供类似的功能?
发布于 2019-01-10 20:39:08
根据this Thoughtbot article,您可以将字符串转换为Capybara::Node::Simple实例。这允许你使用水豚匹配器来对抗它。
我已经创建了一个帮助器方法,它使用以下代码:
def email_html
Capybara.string(mail.html_part.body.to_s)
end然后我可以按如下方式使用它:
expect(email_html).to have_content "5 New Posts"发布于 2016-02-12 05:38:26
未经测试,但您应该能够将Capybara Matcher包含到您的邮件程序规格中(就像Capybara默认情况下查看规格一样),方法是添加
RSpec.configure do |config|
config.include Capybara::RSpecMatchers, :type => :mailer
end然后在你的测试中类似这样的东西
expect(mail.html_part.body.to_s).to have_content('blah blah')
expect(mail.html_part.body.to_s).to have_link('View More', href: posts_url)注意-这会添加匹配器,而不是查找器,因此您可以使用have_link的选项而不是find_link
https://stackoverflow.com/questions/35349650
复制相似问题