WebMock stub request with dynamic body in response

980 Views Asked by At

I am attempting to stub a request with WebMock and have the body of the response expect any value within a given regex; something to the tune of:

stub_request(:get, "someurl").
  with(headers: {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}).
  to_return(status: 200, body: { "data": [{ "id": /\d+/ }] }.to_json)

where id in the response can be any digit of any length. But this does not work. Does anyone know if this is possible?

The reason I am trying this is that there is a restraint that these IDs in question must be unique, and in a test environment I need to be able to create unique IDs and have the response still accept them, without having to manually, explicitly list out every possible digit in this stub_request.

1

There are 1 best solutions below

0
brcebn On

I would suggest to use the lambda on to_return and handle your regex over there.

stub_request(:any, 'www.example.net').
  to_return(lambda do |request| 
    # TODO: check your regex here
    {body: request.body}
  end)

RestClient.post('www.example.net', 'abc')    # ===> "abc\n"