模拟动态生成的对象+ rspec-mock

时间:2017-11-22 15:00:32

标签: rspec-rails rspec-mocks

我正在使用jruby(9.1.12.0)和rspec-rails(3.7.0)。

我有以下方法

class AddressCreator
  include Singleton
  attr_reader :client

  def initialize
    @client = SomeJavaClass.new(some keys go here)       
  end
end

# SomeJavaClass has an create_address instance method.

def create_address(user_id, address)
  req = Java::RandomRequest.new(user_id, address)
  resp = Java::RandomResponse.new(default_response_params)
  AddressCreator.instance.client.create_address(some_key, req, resp)
end

并添加了与

相同的测试
describe '#create_address' do
  let(:some_key) { SecureRandom.uuid }
  let(:user_id) { 1 }
  let(:default_response_params) { false }
  let(:address) { 'some address goes here' }
  let(:request) { Java::RandomRequest.new(address)}
  let(:response) { Java::RandomResponse.new(default_response_params)}

  before {allow(AddressCreator.instance.client).to receive(:create_address).with(some_key, request, response).and_return(response)}

  it 'should create the address' do
    result = AddressCreator.instance.client.create_address some_key
    expect(AddressCreator.singleton).to have_received(:create_address).with(some_key, request, response) do |request|
      expect(request.is_success).to eq(response.is_success)
    end
    expect(result).to eq(response)
  end
end

我的规格未能说明

expected  <Java::RandomRequest:0x1d09fb8e>
got       <Java::RandomRequest:0x38482732>

我们如何模拟以便收到相同的实例?

1 个答案:

答案 0 :(得分:1)

您在规范中创建的Java::RandomRequestJava::RandomResponse的实例与您在create_address中创建的实例不匹配。 尝试对类进行存根以返回所需的值:

let(:request) { instance_double(Java::RandomRequest) }
let(:response) { instance_double(Java::RandomResponse) }
before do
  allow(Java::RandomRequest).to receive(:new).and_return(request)
  allow(Java::RandomResponse).to receive(:new).and_return(response)
end

此外,在allow调用before行动之前调用的间谍后,您可以使用expect... have_receivedcreate_address中展开create_address,例如:

# no before block
it 'should create the address' do
expect(AddressCreator.singleton)
  .to receive(:create_address)
  .with(some_key, request, response) do |request|
    expect(request.is_success).to eq(response.is_success)
  end
  result = AddressCreator.instance.client.create_address some_key
  expect(result).to eq(response)
end

另一种选择是使用kind_of / instance_of / duck_type参数匹配器而不是存根,如果您不打算检查请求和响应的准确性,例如,类似的东西:

# no before
it 'should create the address' do
  expect(AddressCreator.singleton).to receive(:create_address)
  .with(kind_of(String), instance_of(Java::RandomRequest), duck_type(:is_success)) do |request|
    expect(request.is_success).to be_true
  end
  AddressCreator.instance.client.create_address some_key
end

最后,您不必使用真正的安全密钥初始化some_key,如果您不进行处理并且最后只是传递给某个存根类,则double就足够了: let(:some_key) { double }