Skip to content

Instantly share code, notes, and snippets.

@evilstreak
Created July 4, 2014 14:02
Show Gist options
  • Select an option

  • Save evilstreak/aa51c55e3799a2f5d47f to your computer and use it in GitHub Desktop.

Select an option

Save evilstreak/aa51c55e3799a2f5d47f to your computer and use it in GitHub Desktop.

Revisions

  1. evilstreak revised this gist Jul 4, 2014. No changes.
  2. evilstreak created this gist Jul 4, 2014.
    60 changes: 60 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    require 'rspec'

    RSpec.describe Object do
    subject { Object.new }

    before do
    # Stub a method so we can spy on it
    allow(subject).to receive(:a_method)

    # Call it twice with alpha and once with beta
    subject.a_method("alpha")
    subject.a_method("alpha")
    subject.a_method("beta")
    end

    context "with implicit `once`" do
    it "fails with a misleading message" do
    expect(subject).to have_received(:a_method).with("alpha")

    # 1) Object with implicit `once` fails with a misleading message
    # Failure/Error: expect(subject).to have_received(:a_method).with("alpha")
    # #<Object:0x007f914b112a90> received :a_method with unexpected arguments
    # expected: ("alpha")
    # got: ("beta")
    # # ./argument_expectations.rb:18:in `block (3 levels) in <top (required)>'
    end
    end

    context "with explicit `once`" do
    it "fails with a helpful message" do
    expect(subject).to have_received(:a_method).with("alpha").once

    # 2) Object with explicit `once` fails with a helpful message
    # Failure/Error: expect(subject).to have_received(:a_method).with("alpha").once
    # (#<Object:0x007f914b1162a8>).a_method(no args)
    # expected: 1 time with arguments: ("alpha")
    # received: 2 times
    # # ./argument_expectations.rb:24:in `block (3 levels) in <top (required)>'
    end
    end

    context "with explicit `at_least(:once)`" do
    it "passes" do
    expect(subject).to have_received(:a_method).with("alpha").at_least(:once)
    end
    end

    context "with explicit `at_least(3).times`" do
    it "fails with a misleading message" do
    expect(subject).to have_received(:a_method).with("alpha").at_least(3).times

    # 3) Object with explicit `at_least(3).times` fails with a misleading message
    # Failure/Error: expect(subject).to have_received(:a_method).with("alpha").at_least(3).times
    # #<Object:0x007ff89d10a188> received :a_method with unexpected arguments
    # expected: ("alpha")
    # got: ("beta")
    # # ./argument_expectations.rb:50:in `block (3 levels) in <top (required)>'
    end
    end
    end