I tried using this How do I test Pony emailing in a Sinatra app, using rspec? to test a Rails 3.1 app sending emails. The sending works fine, but I'm having a hard time getting the tests to work. Here's what I have so far ...

spec/spec_helper.rb

config.before(:each) do
    do_not_send_email
end
.
.
.
def do_not_send_email
    Pony.stub!(:deliver) # Hijack to not send email.
end

and in my users_controller_spec.rb

it "should send a greeting email" do
    post :create, :user => @attr
    Pony.should_receive(:mail) do |params|
        params[:to].should == "nuser@gmail.com"
        params[:body].should include("Congratulations")
    end
end

and I get this ...

Failures:

1) UsersController POST 'create' success should send a greeting email Failure/Error: Pony.should_receive(:mail) do |params| (Pony).mail(any args) expected: 1 time received: 0 times # ./spec/controllers/users_controller_spec.rb:121:in `block (4 levels) in '

It looks like Pony's not getting an email, but I know the real email is getting sent out.

Any ideas?

有帮助吗?

解决方案

Here's what I finally ended up with for the test ...

it "should send a greeting email" do
    Pony.should_receive(:deliver) do |mail|
        mail.to.should == [ 'nuser@gmail.com' ]
        mail.body.should =~ /congratulations/i
    end
    post :create, :user => @attr
end

The Pony.should_rececieve needs :deliver (not :mail), the do/end was changed a bit, and the post was done after the setup.

Hope this helps someone else.

其他提示

I know this is an old question but there is another way to test this. Version 1.10 of Pony added override_options. Pony uses Mail to send email. override_options lets you use the TestMailer functionality that is built into Mail. So you can set up your test like this:

In spec_helper

require 'pony'
Pony.override_options = { :via => :test }

In your test

before do
  Mail::TestMailer.deliveries.clear
end

it 'some test' do
  # some code that generates an email
  mail = Mail::TestMailer.deliveries.last
  expect(mail.to).to eql 'some@email.com'
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top