RSpec / RSpec Mocks / Docs / Outside rspec
Integrate with Minitest
rspec-mocks is a stand-alone gem that can be integrated with any test framework. The example below demonstrates using rspec-mocks with minitest, but these steps would apply when integrating rspec-mocks with any library or framework:
- Include
RSpec::Mocks::ExampleMethodsin your test context. This provides rspec-mocks' API. - Call
RSpec::Mocks.setupbefore a test begins. - Call
RSpec::Mocks.verifyafter a test completes to verify message expectations. Note that this step is optional; rspec-core, for example, skips this when an example has already failed. - Call
RSpec::Mocks.teardownafter a test completes (and afterverify) to cleanup. This must be called, even if an error has occurred, so it generally goes in anensureclause.
Scenario: Use rspec-mocks with Minitest
- Given a file named "
test/test_helper.rb" with:rubyrequire 'minitest/autorun' require 'rspec/mocks' module MinitestRSpecMocksIntegration include ::RSpec::Mocks::ExampleMethods def before_setup ::RSpec::Mocks.setup super end def after_teardown super ::RSpec::Mocks.verify ensure ::RSpec::Mocks.teardown end end Minitest::Test.send(:include, MinitestRSpecMocksIntegration) - And a file named "
test/rspec_mocks_test.rb" with:rubyrequire 'test_helper' class RSpecMocksTest < Minitest::Test def test_passing_positive_expectation dbl = double expect(dbl).to receive(:message) dbl.message end def test_failing_positive_expectation dbl = double expect(dbl).to receive(:message) end def test_passing_negative_expectation dbl = double expect(dbl).to_not receive(:message) end def test_failing_negative_expectation dbl = double expect(dbl).to_not receive(:message) dbl.message end end - When I run `ruby -Itest test/rspec_mocks_test.rb`
- Then it should fail with the following output:
1) Error: RSpecMocksTest#test_failing_negative_expectation: RSpec::Mocks::MockExpectationError: (Double).message(no args) expected: 0 times with any arguments received: 1 time 2) Error: RSpecMocksTest#test_failing_positive_expectation: RSpec::Mocks::MockExpectationError: (Double).message(*(any args)) expected: 1 time with any arguments received: 0 times with any arguments 4 runs, 0 assertions, 0 failures, 2 errors, 0 skips
Source: features/outside_rspec/minitest.feature at v3.2.1, RSpec Mocks (MIT license).