用 `rspec` 模拟

RSpec 默认使用自己的模拟框架。如果需要,也可以显式配置它。

传递消息期望

假设一个名为“example_spec.rb”的文件,其中包含

RSpec.configure do |config|
  config.mock_with :rspec
end

RSpec.describe "mocking with RSpec" do
  it "passes when it should" do
    receiver = double('receiver')
    expect(receiver).to receive(:message)
    receiver.message
  end
end

我运行 `rspec example_spec.rb`

那么示例应该全部通过。

失败消息期望

假设一个名为“example_spec.rb”的文件,其中包含

RSpec.configure do |config|
  config.mock_with :rspec
end

RSpec.describe "mocking with RSpec" do
  it "fails when it should" do
    receiver = double('receiver')
    expect(receiver).to receive(:message)
  end
end

我运行 `rspec example_spec.rb`

那么输出应该包含“1 个示例,1 个失败”。

待定示例中的失败消息期望(保持待定)

假设一个名为“example_spec.rb”的文件,其中包含

RSpec.configure do |config|
  config.mock_with :rspec
end

RSpec.describe "failed message expectation in a pending example" do
  it "is listed as pending" do
    pending
    receiver = double('receiver')
    expect(receiver).to receive(:message)
  end
end

我运行 `rspec example_spec.rb`

那么输出应该包含“1 个示例,0 个失败,1 个待定”

并且退出状态应为 0。

待定示例中的通过消息期望(失败)

假设一个名为“example_spec.rb”的文件,其中包含

RSpec.configure do |config|
  config.mock_with :rspec
end

RSpec.describe "passing message expectation in a pending example" do
  it "fails with FIXED" do
    pending
    receiver = double('receiver')
    expect(receiver).to receive(:message)
    receiver.message
  end
end

我运行 `rspec example_spec.rb`

那么输出应该包含“FIXED”

那么输出应该包含“1 个示例,1 个失败”

并且退出状态应为 1。

访问 `RSpec.configuration.mock_framework.framework_name`

假设一个名为“example_spec.rb”的文件,其中包含

RSpec.configure do |config|
  config.mock_with :rspec
end

RSpec.describe "RSpec.configuration.mock_framework.framework_name" do
  it "returns :rspec" do
    expect(RSpec.configuration.mock_framework.framework_name).to eq(:rspec)
  end
end

我运行 `rspec example_spec.rb`

那么示例应该全部通过。

双重可以用于生成的描述中

假设一个名为“example_spec.rb”的文件,其中包含

RSpec.configure do |config|
  config.mock_with :rspec
end

RSpec.describe "Testing" do
  # Examples with no descriptions will default to RSpec-generated descriptions
  it do
    foo = double("Test")
    expect(foo).to be foo
  end
end

我运行 `rspec example_spec.rb`

那么示例应该全部通过。