Overhaul mock and stubbing system
The current implementation of mocks, doubles, and stubs is unorganized and has a problematic DSL.
Some of the major problems:
- The stub DSL conflicts with Crystal's syntax. Defining a stub can produce invalid syntax with what looks like acceptable code.
- Unclear errors. This mostly stems from a disorganized implementation and lack of error handling.
- Stubbing existing methods. If you don't match the stub exactly to the original method, it won't overwrite and your stub doesn't work.
- Consistency. I don't think behavior matches RSpec and edge cases produce weird results.
- Lack of documentation in source code...
I would like to overhaul the mock system. These are some ideas that I've come up with.
Change the stub syntax. I think prefix keywords would help clean it up.
Keywords like class
, module
, struct
, and def
should be used.
This will make it explicitly clear to Spectator what is being referenced.
It should also satisfy Crystal syntax parser since macros can accept these AST nodes.
mock class MyClass
stub def foo; end
end
Macros should check what they're given and raise an error when something's not right. I really like how Lucky does this and it's very helpful to new developers.
Check what's being stubbed. Currently, Spectator blindly creates stubbed methods. At the time stubs were initially implemented, Crystal's macro system had very primitive support for "reflection." It has matured quite a bit, and macros now have access to more type information, including methods.
Test test test! Write some tests to verify things still work, then tear it apart. Rewrite it or do whatever it takes to clean up that mess of code.
Since mocks can be invasive, I want to make them opt-in.
Same as how the "should syntax" is opt-in, mocks should be optionally included with require "spectator/mocks"
.
The wiki also needs some TLC on mocks and stubs.
-
Change DSL -
Helpful compiler errors -
Automatic method stub creation -
Tests -
Opt-in with require
-
Wiki