与任何测试框架集成
rspec-mocks 是一个独立的 gem,可以与任何测试框架集成。下面的示例演示了如何将 rspec-mocks 与 minitest 集成,但这些步骤适用于将 rspec-mocks 与任何库或框架集成。
* Include `RSpec::Mocks::ExampleMethods` in your test context. This provides rspec-mocks' API.
* Call `RSpec::Mocks.setup` before a test begins.
* Call `RSpec::Mocks.verify` after 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.teardown` after a test completes (and after `verify`) to cleanup. This
_must_ be called, even if an error has occurred, so it generally goes in an `ensure` clause.
注意:如果您使用的是 minitest,您可能需要使用内置的 minitest 集成。
将 rspec-mocks 与 Minitest 一起使用
假设一个名为“test/test_helper.rb”的文件,其中包含
require '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)
以及一个名为“test/rspec_mocks_test.rb”的文件,其中包含
require '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
def test_passing_positive_spy_expectation
bond = spy
bond.james
expect(bond).to have_received(:james)
end
def test_failing_positive_spy_expectation
bond = spy
expect(bond).to have_received(:james)
end
def test_passing_negative_spy_expectation
bond = spy
expect(bond).not_to have_received(:james)
end
def test_failing_negative_spy_expectation
bond = spy
bond.james
expect(bond).not_to have_received(:james)
end
end
当我运行 ruby -Itest test/rspec_mocks_test.rb
则它应该以以下输出失败
1) 错误 |
RSpecMocksTest#test_failing_negative_expectation |
RSpec::Mocks::MockExpectationError: (Double (anonymous)).message(no args) |
预期:0 次,任何参数 |
收到:1 次 |
2) 错误 |
RSpecMocksTest#test_failing_positive_expectation |
RSpec::Mocks::MockExpectationError: (Double (anonymous)).message(*(any args)) |
预期:1 次,任何参数 |
收到:0 次,任何参数 |
3) 错误 |
RSpecMocksTest#test_failing_positive_spy_expectation |
RSpec::Mocks::MockExpectationError: (Double (anonymous)).james(*(any args)) |
预期:1 次,任何参数 |
收到:0 次,任何参数 |
4) 错误 |
RSpecMocksTest#test_failing_negative_spy_expectation |
RSpec::Mocks::MockExpectationError: (Double (anonymous)).james(no args) |
预期:0 次,任何参数 |
收到:1 次 |
8 个运行,0 个断言,0 个失败,4 个错误,0 个跳过 |