如何为在其中实例化其他类对象的方法编写 rspec

问题描述

我想用ruby为A类的测试方法编写rspec

class A
  def test
    b = B.new
    b.run!
  end
end

class B
  def run!
    return 1
  end
end

有人可以告诉我如何使用模拟来做到这一点

解决方法

你可以这样做:

let(:a) { A.new }
let(:b_mock) { instance_double(B,run!: 'result') }

describe '#test'
  it 'instantiates B and calls #run!' do
    allow(B).to receive(:new).and_return(b_mock)

    a.test

    expect(b_mock).to have_received(:run!)
  end
end

本质上,您想“监视”创建的实例,并检查它是否收到了您期望的方法。

可以也只是测试 A#test 返回 1,但是,这样的测试实际上是在验证 B#run! 的行为,这意味着您的测试是耦合的.

,
b = double(:b,run!: nil)
B.stub(new: b)

expect(b).to receive(:run!)

A.new.test