Created
February 5, 2017 14:27
-
-
Save rdunlop/080a0a5fc790d0d8d61f3c99d6646d5f to your computer and use it in GitHub Desktop.
Example of using RSpec doubles with processor expecting proc
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
source 'https://rubygems.org' | |
gem 'rspec' |
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
class Processor | |
# Receives: | |
# params: a set of arguments which we use | |
# block: a callable proc, which we use for some other need. | |
def initialize(params, block) | |
@params = params | |
@block = block | |
end | |
# execute some complicated logic, returning some result, probably | |
# including some influence from the passed-in block | |
def run | |
@block.call | |
end | |
end |
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
require './processor' | |
describe Processor do | |
let(:params) { {} } | |
context do | |
it "can be called with a block" do # See how the code behaves when we control the result from the block | |
my_code = Proc.new { "some calculation result" } # This block pretends to be what is used in production | |
confirmer = described_class.new(params, my_code) | |
expect(confirmer.run).to eq("some calculation result") # Ensure that the result of confirmer.run is influenced by the result from block.call | |
end | |
it "can ensure it calls the block" do # Ensure that the block is called, without caring about the result | |
my_code = double # RSpec double | |
expect(my_code).to receive(:call).and_return("some result") # Set an expectation, which says: | |
# 1) I expect 'call' to be invoked. (raise an exception at the end of this spec if this isn't true) | |
# 2) I will return 'some result' when that is called. | |
confirmer = described_class.new(params, my_code) | |
confirmer.run | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment