Skip to content

Instantly share code, notes, and snippets.

@stufro
Created May 20, 2023 14:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stufro/b4d70bbf2923ca742db617fe802a6d76 to your computer and use it in GitHub Desktop.
Save stufro/b4d70bbf2923ca742db617fe802a6d76 to your computer and use it in GitHub Desktop.
Crystal Spectator - using `inject_mock`
# spec.cr
require "spectator"
require "./spec_helper"
Spectator.describe OrderCalculator do
inject_mock Database
def_mock(Product)
it "multiplies the product price by given quantity" do
product = new_mock(Product)
allow(Database).to receive(:product).and_return product
allow(product).to receive(:price).and_return 5.0
expect(subject.total_price(quantity: 2)).to eq 10
end
end
# code.cr
class OrderCalculator
def total_price(quantity : Int) : Float
Database.product.price * quantity
end
end
class Product
def price : Float
10.0
end
end
class Database
def self.product : Product
Product.new
end
end
# spec.cr
require "spectator"
require "./spec_helper"
Spectator.describe OrderCalculator do
inject_mock Database
it "multiplies the product price by given quantity" do
allow(Database).to receive(:product_price).and_return 5.0
expect(subject.total_price(quantity: 2)).to eq 10
end
end
# code.cr
class OrderCalculator
def total_price(quantity : Int) : Float
Database.product_price * quantity
end
end
class Database
def self.product_price : Float
0.0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment