gpt4 book ai didi

ruby-on-rails - 在 Rspec 中 stub ActionMailer

转载 作者:数据小太阳 更新时间:2023-10-29 06:53:13 26 4
gpt4 key购买 nike

致敬!
我正在尝试使用如下所示的 Rspec 测试 Controller 方法:

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

相应的规范如下所示:

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

当测试运行时,我收到这条消息:

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)>'

我在整个 Controller 方法和 email_customer 方法中分散了 puts 语句,所以我知道它最终会运行它的过程并使用正确的方法,但我不确定为什么它会失败。我猜这是一个我不确定的愚蠢语法错误。预先感谢您的帮助!

最佳答案

消息 expect 应出现在对您要测试的方法的调用之前,因为它们实际上将消息 stub 在对象中:

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

关于ruby-on-rails - 在 Rspec 中 stub ActionMailer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24919622/

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