Skip to content

Instantly share code, notes, and snippets.

@ssaunier
Last active December 24, 2015 21:19
Show Gist options
  • Save ssaunier/6864350 to your computer and use it in GitHub Desktop.
Save ssaunier/6864350 to your computer and use it in GitHub Desktop.
Prevent stubbing nonexistant method with rspec-fire and rspec-mocks. Discussed at http://sebastien.saunier.me/blog/2013/10/06/on-testing.html
class God
#Imagine the welcome person has been removed
# def welcome_person(person)
# end
end
class Person
def initialize(god)
@god = god
end
# Then the API contract from God to Person is broken
def die
@god.welcome_person(self)
end
end
# rspec-mock
describe Person do
context "Using rspec-mock, when a person die" do
it "God should welcome him (incorrect test)" do # GREEN (but should not)
god = double("god")
god.stub(:welcome_person) # rspec-mock does not check if God actually implements it.
person = Person.new(god)
god.should_receive(:welcome_person).with(person)
person.die
end
it "God should welcome him (correct test)" do # RED (as it should)
god = God.new
person = Person.new(god)
god.should_receive(:welcome_person).with(person).and_call_original # Actually calls God implementation
person.die
end
end
end
###################################
require 'rspec/fire'
RSpec.configure do |config|
config.include(RSpec::Fire)
end
# rspec-fire
describe Person do
context "Using rspec-fire, when a person die" do
it "God should welcome him" do # RED (as it should)
god = instance_double "God"
person = Person.new(god)
god.should_receive(:welcome_person).with(person)
person.die
end
end
end
source 'https://rubygems.org'
ruby "2.0.0"
gem "rspec"
gem "rspec-mocks"
gem "rspec-fire"
$ bundle exec rspec _rspec.rb
.FF
Failures:
1) Person Using rspec-mock, when a person die God should welcome him (correct test)
Failure/Error: @god.welcome_person(self)
NoMethodError:
undefined method `welcome_person' for #<God:0x007f82d9cba918>
# ./rspec.rb:14:in `die'
# ./rspec.rb:34:in `block (3 levels) in <top (required)>'
2) Person Using rspec-fire, when a person die God should welcome him
Failure/Error: god.should_receive(:welcome_person).with(person)
God does not implement:
welcome_person
# ./rspec.rb:52:in `block (3 levels) in <top (required)>'
Finished in 0.0014 seconds
3 examples, 2 failures
Failed examples:
rspec ./rspec.rb:30 # Person Using rspec-mock, when a person die God should welcome him (correct test)
rspec ./rspec.rb:49 # Person Using rspec-fire, when a person die God should welcome him
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment