Show new mock and double system in README

This commit is contained in:
Michael Miller 2022-07-12 23:22:47 -06:00
parent 754bfd6939
commit e52f187eb7
No known key found for this signature in database
GPG key ID: 32B47AE8F388A1FF
2 changed files with 64 additions and 9 deletions

View file

@ -255,19 +255,40 @@ end
Spectator supports an extensive mocking feature set via two types - mocks and doubles. Spectator supports an extensive mocking feature set via two types - mocks and doubles.
Mocks are used to override behavior in existing types. Mocks are used to override behavior in existing types.
Doubles are objects that stand-in when there are no type restrictions. Doubles are objects that stand-in when there are no type restrictions.
Stubs can be defined on both that control how methods behave. Stubs can be defined on both which control how methods behave.
```crystal ```crystal
double :my_double do abstract class Interface
stub foo : Int32 abstract def invoke(thing) : String
stub bar(arg) { arg.to_s }
end end
it "does a thing" do # Type being tested.
class Driver
def do_something(interface : Interface, thing)
interface.invoke(thing)
end
end
Spectator.describe Driver do
# Define a mock for Interface.
mock Interface
# Define a double that the interface will use.
double(:my_double, foo: 42)
it "does a thing" do
# Create an instance of the mock interface.
interface = mock(Interface)
# Indicate that `#invoke` should return "test" when called.
allow(interface).to receive(:invoke).and_return("test")
# Create an instance of the double.
dbl = double(:my_double) dbl = double(:my_double)
allow(dbl).to receive(:foo).and_return(42) # Call the mock method.
expect(dbl.foo).to eq(42) subject.do_something(interface, dbl)
expect(dbl.bar(42)).to eq("42") # Verify everything went okay.
expect(interface).to have_received(:invoke).with(thing)
end
end end
``` ```

34
spec/docs/readme_spec.cr Normal file
View file

@ -0,0 +1,34 @@
require "../spec_helper"
private abstract class Interface
abstract def invoke(thing) : String
end
# Type being tested.
private class Driver
def do_something(interface : Interface, thing)
interface.invoke(thing)
end
end
Spectator.describe Driver do
# Define a mock for Interface.
mock Interface
# Define a double that the interface will use.
double(:my_double, foo: 42)
it "does a thing" do
# Create an instance of the mock interface.
interface = mock(Interface)
# Indicate that `#invoke` should return "test" when called.
allow(interface).to receive(:invoke).and_return("test")
# Create an instance of the double.
dbl = double(:my_double)
# Call the mock method.
subject.do_something(interface, dbl)
# Verify everything went okay.
expect(interface).to have_received(:invoke).with(dbl)
end
end