2016-02-11 20 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的主體字符串 –

相關問題