2

我正在使用 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>

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

4

1 回答 1

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

此外,您可以在调用之前调用一个allowbefore操作expect... have_received之前create_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_ofduck_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 }

于 2017-11-27T08:02:36.437 回答