rspec / rspec-expectations

Provides a readable API to express expected outcomes of a code example
https://rspec.info
MIT License
1.26k stars 396 forks source link

`return_value` matcher #1466

Open pirj opened 2 months ago

pirj commented 2 months ago

I have a proof of concept of a matcher that works with block expectations, but checks the value returned by the block. Works as a compound matcher, too:

$bar = 0
def foo
  $bar += 1
  2
end

RSpec.describe do
  it do
    $bar=0
    expect { foo }
      .to change { $bar }.to(1)
      .and return_value(2)
  end

  it do
    $bar=0
    expect { foo }
      .to return_value(satisfy { |x| x == 2 })
      .and change { $bar }.to(1)
  end
end

Existing known alternatives:

expect {
  expect(foo).to eq(2)
}.to change { $bar }.to(1)

PS it took me five years

Is this something worth continuing working on, WDYT @JonRowe ?

JonRowe commented 2 months ago

I think I'd rather eq supported both block and value type of expectations e.g.

$bar=0
    expect { foo }
      .to change { $bar }.to(1)
      .and eq(2)
pirj commented 2 months ago

Maybe satisfy without/with a block? That would allow passing composed matchers:

    $bar=0
    expect { foo }
      .to change { $bar }.to(1)
      .and satisfy(eq(2))

    $bar=0
    expect { foo }
      .to change { $bar }.to(1)
      .and satisfy { |baz| baz == 2 }