With rspec how do I test a method received a hash parameter in the correct order?

StackOverflow https://stackoverflow.com/questions/19898582

  •  30-07-2022
  •  | 
  •  

質問

Unfortunately I'm needing to interact with a Soap API. If that's not bad enough, the API has parameter ordering turned on which means, regardless of the fact it's XML, it must be structured in the correct element order.

I'm using Savon so I'm building an ordered hash. However after some refactoring, the real calls stopped working whilst all my tests continued to pass. A typical test looks like this:

it 'should receive correctly ordered hash' do
  example_id = 12345789
  our_api = Example::ApiGateway.new()
  params = {:message=>{'ApiKey' => api_key, 'ExampleId' => example_id}}
  Savon::Client.any_instance.should_receive(:call).with(:get_user_details, params).and_return(mocked_response())
  our_api.get_user(example_id: example_id)
end

The hash compare totally does not care about the order of the keys so this test passes regardless of the actual hash order received. I'd like the just grab the parameters that the call method receives and then I could compare the ordered keys of each hash but I con't find how to do this.

How do I make sure that the Savon call receives the message hash in the correct order?

役に立ちましたか?

解決

So in the next google I found the answer. should_receive can take a block, so I can rebuild my test as

it 'should receive correctly ordered hash' do
  example_id = 12345789
  our_api = Example::ApiGateway.new()
  params = {:message=>{'ApiKey' => api_key, 'ExampleId' => example_id}}
  Savon::Client.any_instance.should_receive(:call){ |arg1, arg2|
     arg1.should eq(:get_user_details)
     #Ensure order here manually
     arg2[:message].keys.should eq(params[:message].keys)
     mocked_response()
  }
  our_api.get_user(example_id: example_id)
end

Now my tests will break as expected when the keys get messed with and I can rack up yet more hours to working around other peoples's fragile code...

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top