Minitest 集成

rspec-expectations 是一个独立的 gem,可以在不使用其他 RSpec 的情况下使用。如果你喜欢使用 minitest 作为你的测试运行器,但更喜欢 RSpec 对表达期望的方式,你可以同时使用两者。

要将 rspec-expectations 与 minitest 集成,请使用 rspec/expectations/minitest_integration

在 minitest 中使用 rspec/expectations

给定 一个名为“rspecexpectationstest.rb”的文件,其中包含

require 'minitest/autorun'
require 'rspec/expectations/minitest_integration'

class RSpecExpectationsTest < Minitest::Test
  RSpec::Matchers.define :be_an_integer do
    match { |actual| Integer === actual }
  end

  def be_an_int
    # This is actually an internal rspec-expectations API, but is used
    # here to demonstrate that deprecation warnings from within
    # rspec-expectations work correctly without depending on rspec-core
    RSpec.deprecate(:be_an_int, :replacement => :be_an_integer)
    be_an_integer
  end

  def test_passing_expectation
    expect(1 + 3).to eq 4
  end

  def test_failing_expectation
    expect([1, 2]).to be_empty
  end

  def test_custom_matcher_with_deprecation_warning
    expect(1).to be_an_int
  end

  def test_using_aggregate_failures
    aggregate_failures do
      expect(1).to be_even
      expect(2).to be_odd
    end
  end
end

我运行 ruby rspec_expectations_test.rb

那么 输出应该包含“4 runs, 5 assertions, 2 failures, 0 errors”

并且 输出应该包含“expected [1, 2].empty? to be truthy, got false”

并且 输出应该包含“beanint is deprecated”

并且 输出应该包含“Got 2 failures from failure aggregation block”。

在 minitest/spec 中使用 rspec/expectations

给定 一个名为“rspecexpectationsspec.rb”的文件,其中包含

require 'minitest/autorun'
require 'minitest/spec'
require 'rspec/expectations/minitest_integration'

describe "Using RSpec::Expectations with Minitest::Spec" do
  RSpec::Matchers.define :be_an_integer do
    match { |actual| Integer === actual }
  end

  it 'passes an expectation' do
    expect(1 + 3).to eq 4
  end

  it 'fails an expectation' do
    expect([1, 2]).to be_empty
  end

  it 'passes a block expectation' do
    expect { 1 / 0 }.to raise_error(ZeroDivisionError)
  end

  it 'fails a block expectation' do
    expect { 1 / 1 }.to raise_error(ZeroDivisionError)
  end

  it 'passes a negative expectation (using `not_to`)' do
    expect(1).not_to eq 2
  end

  it 'fails a negative expectation (using `to_not`)' do
    expect(1).to_not eq 1
  end

  it 'fails multiple expectations' do
    aggregate_failures do
      expect(1).to be_even
      expect(2).to be_odd
    end
  end

  it 'passes a minitest expectation' do
    expect(1 + 3).must_equal 4
  end

  it 'fails a minitest expectation' do
    expect([1, 2]).must_be :empty?
  end
end

我运行 ruby rspec_expectations_spec.rb

那么 输出应该包含“9 runs, 10 assertions, 5 failures, 0 errors”

并且 输出应该包含“expected [1, 2].empty? to be truthy, got false”

并且 输出应该包含“expected ZeroDivisionError but nothing was raised”

并且 输出应该包含“Got 2 failures from failure aggregation block”

并且 输出应该包含“Expected [1, 2] to be empty?”.