Skip to content

Conversation

@seanpdoyle
Copy link
Contributor

Extend the ActiveResource::HttpMock declaration DSL to accept a block argument.

When passed a block, the mock will yield an ActiveResource::Request instance to the block it handles a matching request.

def setup
  @matz = { person: { id: 1, name: "Matz" } }

  ActiveResource::HttpMock.respond_to do |mock|
    mock.get "/people.json", omit_query_params: true do |request|
      if request.path.split("?").includes?("name=Matz")
        { people: [ @matz ] }.to_json
      else
        { people: [] }.to_json
      end
    end
  end
end

def test_get_matz
  people = Person.where(name: "Matz")
  assert_equal [ "Matz" ], people.map(&:name)
end

When a block is passed to the mock, it ignores the body, status, and response_headers arguments.

Extend the `ActiveResource::HttpMock` declaration DSL to accept a block
argument.

When passed a block, the mock will yield an `ActiveResource::Request`
instance to the block it handles a matching request.

```ruby
def setup
  @matz = { person: { id: 1, name: "Matz" } }

  ActiveResource::HttpMock.respond_to do |mock|
    mock.get "/people.json", omit_query_params: true do |request|
      if request.path.split("?").includes?("name=Matz")
        { people: [ @matz ] }.to_json
      else
        { people: [] }.to_json
      end
    end
  end
end

def test_get_matz
  people = Person.where(name: "Matz")
  assert_equal [ "Matz" ], people.map(&:name)
end
```

When a block is passed to the mock, it ignores the `body`, `status`, and
`response_headers` arguments.
@rafaelfranca rafaelfranca merged commit c71ca22 into rails:main Oct 23, 2025
19 checks passed
@seanpdoyle seanpdoyle deleted the http-mock-block branch October 23, 2025 19:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants