Last active
August 29, 2015 14:00
-
-
Save sheldonh/11248816 to your computer and use it in GitHub Desktop.
rspec spies: spy on unstubbed method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This spec demonstrates how rspec's and_call_original | |
| # allows spying on real objects without affecting their | |
| # behaviour. In the following output from rspec, note | |
| # that real output ("Moo!") actually goes to $stdout, | |
| # even though the latter's puts method was stubbed. | |
| # | |
| # Cow | |
| # before it speaks | |
| # is considered quiet | |
| # when it speaks | |
| # Moo! | |
| # prints Moo! to the standard output stream | |
| # Moo! | |
| # is not considered quiet | |
| # | |
| # Finished in 0.00257 seconds | |
| # 3 examples, 0 failures | |
| require 'spec_helper' | |
| class Cow | |
| def initialize(io = $stdout) | |
| @io = io | |
| @quiet = true | |
| end | |
| def say | |
| @io.puts "Moo!" | |
| @quiet = false | |
| end | |
| def quiet? | |
| @quiet | |
| end | |
| end | |
| describe Cow do | |
| let(:stdout) do | |
| $stdout.tap { |io| allow(io).to receive(:puts).and_call_original } | |
| end | |
| subject { Cow.new(stdout) } | |
| context "before it speaks" do | |
| it "is considered quiet" do | |
| expect(subject).to be_quiet | |
| end | |
| end | |
| context "when it speaks" do | |
| before(:each) { subject.say } | |
| it "prints Moo! to the standard output stream" do | |
| expect(stdout).to have_received(:puts).with("Moo!") | |
| end | |
| it "is not considered quiet" do | |
| expect(subject).to_not be_quiet | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment