0
\$\begingroup\$

Any time I'm testing a Ruby class that calls a Kernel method such as sleep or exit, i define a singleton method on the class instance and test that it has been invoked:

it "must throttle requests" do
  sleep_was_called = false

  subject.define_singleton_method(:sleep) { |seconds|
    sleep_was_called = true
  }

  subject.request query
  subject.request query

  sleep_was_called.must_equal true
end

I have seen far more sophisticated method stub testing in RSpec, but it there a more fancy and less verbose way to do this using MiniTest?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This seems like more of an SO type question. \$\endgroup\$ – Mark Thomas Jun 14 '13 at 12:02
3
\$\begingroup\$

I know MiniTest has an expectations framework, but I'm not familiar with it. I use rspec-expectations to accomplish this, like so:

describe ClassName do
  let(:subject) { described_class.new }

  describe '#method' do
    it 'should sleep 3 times and output hello world' do
      expect(subject).to receive(:sleep).exactly(3).times
      expect(subject).to receive(:puts).with('Hello world!').exactly(3).times

      subject.method
    end
  end
end

I know this doesn't directly answer your question, but my hope is it leads you in the right direction.

\$\endgroup\$
1
  • \$\begingroup\$ However, it's not a great idea to do this much. It's normally better to test behavior, not implementation, except in a few special cases. \$\endgroup\$ – Marnen Laibow-Koser Jun 6 '14 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.