如何在 rspec 邮件程序中设置 header_cookies

How to set header_cookies in rspec mailers

在我的邮件程序中,我使用 header_cookies(从控制器传递)为附件生成 pdf 文件。如何在 articles_spec.rb 测试中生成 header_cookies

文章邮寄者:

class ArticlesMailer < ActionMailer::Base

  def send_article(article, header_cookies)
    @article = article
    @user = @article.user
    attachments['article.pdf'] = prepare_pdf_file

    mail(
      subject: "Article №#{@article.id}",
      to: @user.email
    )
  end

  def prepare_pdf_file(header_cookies)
    Grover.new(pdf_view_article_url(@article), cookies: header_cookies).to_pdf
  end
end

文章控制器

def create
   @articele = Article.new(article_params)
   if @article.save
      ArticlesMailer.send_article(@article, header_cookies).deliver_now
   else
      render :new
   end
end

artilces_spec.rb

RSpec.describe ArticlesMailer, type: :mailer do
  describe "send_article" do
    let!(:admin) { create(:user, :superadmin) }
    let!(:article) { create(:article, user: admin) }
    let!(:mail) { ArticlesMailer.send_article(article, header_cookies) }
    let(:article_preview_page) { preview_article_path(user_id: admin.id, id: article.id) }

    it "renders the headers" do
      expect(mail.subject).to eq("Article №#{article.id}")
      expect(mail.to).to eq admin.email
    end

    it "renders the body" do
      expect(mail.body.encoded).to match("Hi #{admin.name}")
    end
  end
end

您是否尝试创建 header_cookies 对象并将其传递给 send_article 调用?

  let!(:header_cookies) do
    [
      { name: 'sign_username', value: 'any@any.com', domain: 'mydomain' },
      { name: '_session_id', value: '9c014df0b699d8dc08d1c472f8cc594c', domain: 'mydomain' }
    ]
  end