简体   繁体   English

如何测试使用 Minitest 调用的方法?

[英]How to test a method is called with Minitest?

class Post
  def save
    Mailer.notify!('bla')
    true
  end
end

How to test that when post.save is called, the Mailer.notify method is fired?如何测试时post.save被调用时, Mailer.notify方法解雇? and with the right arguments.并有正确的论据。

With RSpec I usually do:使用 RSpec 我通常会这样做:

expect(Mailer).to receive(:notify!).with('bla')
post.save

Thank you in advance!提前谢谢你!

You can do something like this:你可以这样做:

describe 'Post#save' do
  it "calls Mailer::notify!" do
    mock = MiniTest::Mock.new
    mock.expect(:call, nil, ['bla'])

    Mailer.stub(:notify!, mock) do
      post.save
    end

    mock.verify
  end
end

And yes, that is easier and more intuitive in RSpec...是的,这在 RSpec 中更简单、更直观......

For mocking with minitest I like using Mocha gem https://github.com/freerange/mocha对于 minitest 的模拟,我喜欢使用 Mocha gem https://github.com/freerange/mocha

I will be:我将是:

Mailer.expects(:notify!).with('bla').at_least_once

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

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