I have been working on a project recently where modules are used extensively to share behaviour between model classes. I was looking to use an example from the system but they were all overly complex and detracted from the subject - testing modules. So in the following contrived example I will show you how to test the behavior of a module using rspec. The following “Pointless” module adds a class method which will scramble a class name…. doesn’t get more pointless than that!
1 2 3 4 5 6 7 8 9
Below the module is mixed into two active record classes.
1 2 3
1 2 3
When testing modules I tend to add a folder under the spec directory called modules. I then use the shared_examples_for group and define specs within the block. When calling described_class it returns the class that the module has been mixed into within the current it_behaves_like context.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
It’s then just a matter of using describe for each class the module has been mixed into and call it_behaves_like Module, then the specs for the module will be run in the context of the class.