RSpec shared examples with template methods
It’s pretty common to have multiple tests that are nearly the same.
In one app, we support bidding on both online and hammer auctions (auctions with people physically present). They’re separate controllers but with a lot of shared code and behavior.
We want to test both, but we’d rather not write two almost identical tests if we can help it.
So we’ve been using RSpec shared examples, with the template method patternto account for the differences, and we like it.
Here’s a simplified example:
spec/request/online_bidding_spec.rb
1
2
3
4
5
6
7
8
9
10
11
12
|
|
spec/request/hammer_bidding_spec.rb
1
2
3
4
5
6
7
8
9
10
11
12
|
|
spec/support/shared_examples/bidding.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
|
The only template method here is auction_path
. The shared example makes sure, by raising, that it’s overridden in your concrete specs.