Ответ 1
Вы можете проверить ActionMailer:: Base.deliveries.count, чтобы убедиться, что он увеличился на 1.
Что-то вроде этого (untested)
expect {custom_mailer.deliver}.to change { ActionMailer::Base.deliveries.count }.by(1)
В настоящее время в моей спецификации контроллера у меня есть:
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
В моем контроллере я:
# 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: "[email protected]", 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.
Что-то вроде этого (untested)
expect {custom_mailer.deliver}.to change { ActionMailer::Base.deliveries.count }.by(1)
Созданные вами макеты не соответствуют тому, что на самом деле выполняется. Фактически вы должны называть deliver
этим макетом, который вы создаете.
Что-то вроде
message = mock('Message')
CustomerMailer.should_receive(:sales_alert).and_return(message)
message.should_receive(:deliver)
должен пройти.
Если вы хотите проверить, что передано sales_alert
, то, что вы делаете, не будет работать - активная запись только когда-либо сравнивает объекты по принципу первичного ключа, поэтому клиентский билет, который вы создаете в спецификации, не будет равный той, что была создана в вашем контроллере.
Одна вещь, которую вы можете сделать, это
CustomerMailer.should_receive(:sales_alert) do |arg|
...
end.and_return(message)
rspec будет выдавать любые sales_alert
, и вы можете делать любые проверки, которые вы хотите
Другой способ сделать это - заглушить CustomerTicket.new
, чтобы затем вы могли управлять тем, что он возвращает, например
mock_ticket = mock(CustomerTicket)
CustomerTicket.should_receive(:new).with(customer_ticket_attributes).and_return(mock_ticket)
mock_ticket.should_receive(:save).and_return(true)
CustomerMailer.should_receive(:sales_alert).with(mock_ticket).and_return(message)
Наконец, вы можете решить, что эта отправка предупреждений должна действительно принадлежать методу экземпляра CustomerTicket
, и в этом случае спецификация вашего контроллера может просто проверить, что метод send_sales_alert
был вызван в билет.
Это способ проверки того, что Mailer вызывается с правильными аргументами.
delivery = double
expect(delivery).to receive(:deliver_now).with(no_args)
expect(CustomerMailer).to receive(:sales_alert)
.with(customer_ticket)
.and_return(delivery)