Issues with RSpec mocks
Lets start from example:
1 2 3 4 5 6 7 8 | |
And its corresponding spec:
1 2 3 4 5 6 7 8 9 10 11 | |
Pretty straightforward unit test for Example#do_something. But if you run rspec you will get:
1 2 3 4 5 | |
It happens because class contracts use #is_a? to determine if contract matches or not. Simply: something.is_a?(Something) is required to be true.
But if we try to do it with instance_double, that is what we get:
1 2 3 4 | |
Solution to problem
Pretty straightforward one:
1 2 3 4 5 6 7 8 | |
But this can be boring to type it each time you need an instance_double while working with contracts. So here you go:
1 2 3 4 | |
Run bundle to install contracts-rspec gem.
1 2 3 4 5 6 7 8 | |
Now you are covered. Inclusion of Contracts::RSpec::Mocks slightly alters behavior of instance_double. Now it automatically stubs out #is_a?(Klass) to return true on the class it was created from. In our case Something. This happens here: https://github.com/waterlink/contracts-rspec/blob/master/lib/contracts/rspec/mocks.rb#L4-L8
You can include it only in contexts you need, or you can do it globally from spec_helper like you do usually include spec helpers.
Links
- Gem: https://github.com/waterlink/contracts-rspec
- contracts.ruby: https://github.com/egonSchiele/contracts.ruby
- contracts.ruby chat: https://gitter.im/egonSchiele/contracts.ruby
- Born from here: egonSchiele/contracts.ruby#14
- Introduction to contracts.ruby
- Great contracts.ruby tutorial
Thanks!
If you have any questions, suggestions or just want to chat about how contracts.ruby is awesome, you can ping me on twitter @tdd_fellow. If you have any issues using contracts.ruby or contracts-rspec you can create issues on corresponding github project. Pull requests are welcome!