gpt4 book ai didi

ruby-on-rails - 如何编写确保发送电子邮件的Rspec Controller 测试?

转载 作者:行者123 更新时间:2023-12-04 03:04:56 27 4
gpt4 key购买 nike

目前在我的 Controller 规范中,我有:

require 'spec_helper'

describe CustomerTicketsController do
login_user

describe "POST /create (#create)" do
# include EmailSpec::Helpers
# include EmailSpec::Matchers
it "should deliver the sales alert email" do
# expect
customer_ticket_attributes = FactoryGirl.attributes_for(:customer_ticket)
customer_mailer = mock(CustomerMailer)
customer_mailer.should_receive(:deliver).
with(CustomerTicket.new(customer_ticket_attributes))
# when
post :create, :customer_ticket => customer_ticket_attributes
end
end
end

在我的 Controller 中,我有:
  # POST /customer_tickets
# POST /customer_tickets.xml
def create
respond_to do |format|
if @customer_ticket.save
CustomerMailer.sales_alert(@customer_ticket).deliver
format.html { redirect_to @customer_ticket, notice: 'Customer ticket was successfully created.' }
format.xml { render xml: @customer_ticket, status: :created, location: @customer_ticket }
else
format.html { render action: "new" }
format.xml { render xml: @customer_ticket.errors, status: :unprocessable_entity }
end
end
end

我的测试当前产生以下输出:

Failures:

1) CustomerTicketsController POST /create (#create) should deliver the sales alert email
Failure/Error: customer_mailer.should_receive(:deliver).
(Mock CustomerMailer).deliver(#<CustomerTicket id: nil, first_name: "firstname1", last_name: "lastname1", company: nil, referral: nil, email: "firstname1@example.com", phone: "555-5555", fax: nil, country: nil, address1: "555 Rodeo Dr.", address2: nil, city: "Beverly Hills", state: "CA", postcode: "90210", question: "The answer to the universe is 4.", type: nil, status: nil, priority: nil, number: nil, cs_rep_id: nil, created_at: nil, updated_at: nil>)
expected: 1 time
received: 0 times
# ./spec/controllers/customer_ticket_controller_spec.rb:13:in `block (3 levels) in <top (required)>'

Finished in 0.52133 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/controllers/customer_ticket_controller_spec.rb:9 # CustomerTicketsController POST /create (#create) should deliver the sales alert email


谢谢您的光临。

最佳答案

您可以检查ActionMailer::Base.deliveries.count以确保它已增加1。

像这样(未经测试)

expect {custom_mailer.deliver}.to change { ActionMailer::Base.deliveries.count }.by(1)

关于ruby-on-rails - 如何编写确保发送电子邮件的Rspec Controller 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10884302/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com