Created
July 21, 2015 11:38
-
-
Save jpmoral/b1a5c60c472af4a50018 to your computer and use it in GitHub Desktop.
extend vs. include in spec form
This file contains 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
module Motion | |
def default_movement | |
"walking" | |
end | |
end | |
module Flight | |
extend Motion | |
def movement | |
"flying" | |
end | |
end | |
module Swimming | |
include Motion | |
def movement | |
"swimming" | |
end | |
end | |
module Speech | |
def greet | |
"Hello World" | |
end | |
end | |
class Person | |
extend Motion | |
include Speech | |
end | |
class Bird | |
include Flight | |
end | |
class Fish | |
include Swimming | |
end | |
class Cat; end |
This file contains 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 "rspec" | |
require_relative "modules" | |
RSpec.describe "Ruby composition methods" do | |
describe "a class" do | |
context "when it extends a module" do | |
it "adds the module methods to the class's class methods" do | |
expect(Person.default_movement).to eq("walking") | |
end | |
it "does not add the module methods to the class's instance methods" do | |
person = Person.new | |
expect { person.default_movement }.to raise_error(NoMethodError) | |
end | |
end | |
context "when it includes a module" do | |
it "add the module methods to the class's instance methods" do | |
person = Person.new | |
expect(person.greet).to eq("Hello World") | |
end | |
end | |
end | |
describe "a module" do | |
context "when it extends another module" do | |
it "adds the other module's methods to the original module's class methods" do | |
bird = Bird.new | |
expect(bird.movement).to eq("flying") | |
expect { bird.default_movement }.to raise_error(NoMethodError) | |
end | |
end | |
context "when it includes another module" do | |
it "adds the other module's methods to the original module's instance methods" do | |
fish = Fish.new | |
expect(fish.movement).to eq("swimming") | |
expect(fish.default_movement).to eq("walking") | |
end | |
end | |
end | |
describe "an object" do | |
context "when it extends a module" do | |
it "gains the modules methods" do | |
cat = Cat.new | |
cat.extend(Speech) | |
expect(cat.greet).to eq("Hello World") | |
end | |
end | |
it "cannot include modules" do | |
cat = Cat.new | |
expect { cat.include }.to raise_error(NoMethodError) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment