DEV Community

loading...

RSpec: what's important for the test

vasily profile image Vasily Polovnyov ・1 min read

Situation: we need to make sure that we charge the user the correct amount when he uses a coupon. Important point: the class responsible for this has a huge API with mandatory arguments.

First take:

context "when coupon is applied" do
  it "charges user $500" do
    allow(Cashier).to receive(:charge)

    purchase.perform

    expect(Cashier).to have_received(:charge)
      .with(
        user: user,
        sum: 500,
        description: "season ticket purchase",
        coupon: coupon
      )
  end
end
Enter fullscreen mode Exit fullscreen mode

If we leave the test as it is, it will distract us with details that are not important: the user, the description of the charge, the coupon. Since we want to make sure that the amount has changed, we only need to check the amount:

context "when coupon is applied" do
  context "charges user $500" do
    allow(Cashier).to receive(:charge)

    purchase.perform

    expect(Cashier).to have_received(:charge)
      .with(hash_including(sum: 500))
  end
end
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide