简体   繁体   English

在Rspec中存根ActionMailer

[英]Stubbing ActionMailer in Rspec

Salutations! 敬礼!
I'm trying to test a controller method with Rspec that looks like this: 我正在尝试用Rspec测试一个控制器方法,如下所示:

def email_customer
  @quote = Quote.find(params[:quote_id])
  hash = {
    quote: @quote,
    body: params[:email_body],
    subject: params[:email_subject]
  }
  QuoteMailer.email_customer(hash).deliver
  redirect_to edit_quote_path params[:quote_id]
end

And the corresponding spec looks like this: 相应的规范如下所示:

describe 'POST email_customer' do
  let!(:quote) { create(:valid_quote) }
  it 'assigns the quote and sends the customer an email' do
    post :email_customer, quote_id: quote.id
    expect(assigns(:quote)).to eq(quote)
    expect(QuoteMailer).to receive(:email_customer).with(an_instance_of(Hash)).and_return( double('QuoteMailer', deliver: true))
  end
end

When the test runs though, I get this message: 当测试运行时,我收到此消息:

Failure/Error: expect(QuoteMailer).to receive(:email_customer).with(an_instance_of(Hash)).and_return( double('QuoteMailer', deliver: true))
       (<QuoteMailer (class)>).email_customer(an instance of Hash)
           expected: 1 time with arguments: (#<RSpec::Matchers::AliasedMatcher:0x0000000c2b1e28 @description_block=#<Proc:0x00000009816268@/home/david/.rvm/gems/ruby-2.1.1/gems/rspec-expectations-3.0.0.beta2/lib/rspec/matchers.rb:231 (lambda)>, @base_matcher=#<RSpec::Matchers::BuiltIn::BeAnInstanceOf:0x0000000c2b1e50 @expected=Hash>>)
           received: 0 times with arguments: (#<RSpec::Matchers::AliasedMatcher:0x0000000c2b1e28 @description_block=#<Proc:0x00000009816268@/home/david/.rvm/gems/ruby-2.1.1/gems/rspec-expectations-3.0.0.beta2/lib/rspec/matchers.rb:231 (lambda)>, @base_matcher=#<RSpec::Matchers::BuiltIn::BeAnInstanceOf:0x0000000c2b1e50 @expected=Hash>>)
     # ./spec/controllers/quotes_controller_spec.rb:28:in `block (3 levels) in <top (required)>'

I've scattered puts statements throughout the controller method as well as the email_customer method so I know that it ends up running its course and using the right method, but I'm not sure why its failing this. 我在整个控制器方法和email_customer方法中分散了put语句,因此我知道它最终会运行它的路线并使用正确的方法,但我不确定为什么它会失败。 I'm guessing its a stupid syntax error that I'm not sure about. 我猜它是一个我不确定的愚蠢的语法错误。 Thanks in advance for your help! 在此先感谢您的帮助!

Message expect ations should appear before the call to the method you want to test, since they actually stub the message in the object: 消息expect在调用要测试的方法之前出现,因为它们实际上是在对象中存根消息:

describe 'POST email_customer' do
  let!(:quote) { create(:valid_quote) }
  it 'assigns the quote and sends the customer an email' do
    expect(QuoteMailer).to receive(:email_customer).with(an_instance_of(Hash)).and_return( double('QuoteMailer', deliver: true))

    post :email_customer, quote_id: quote.id

    expect(assigns(:quote)).to eq(quote)
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM