2016-02-11 19 views
0

我遇到过一些工具,可以更容易地测试Rails应用程序中生成的电子邮件,但它们被设计用于集成测试(即capybara-email)。但是,我正在编写一个可直接与邮件程序一起工作的单元测试。如何测试由Rails邮件程序生成的html内容?

目前,我有我的邮件测试,看起来是这样的:

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 ["[email protected]"] 
    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 

我不知道是否有使用水豚直接达到这样的一种方式。也许有替代品可以提供类似的功能?

回答

0

未经检验的,但你应该能够通过添加

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

+0

嗯...不幸的是,这并不因为'mail.html_part'母鹿工作s不回应'has_content?' – Andrew

+0

ummm ---它不应该调用has_content?在它上面,除非html_part没有返回一个字符串 - 我将不得不检查 - 更新来访问html_part的主体字符串 –

相关问题