Instantly share code, notes, and snippets.

Embed
What would you like to do?
extend vs. include in spec form
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
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