I would like to know how to write unit tests for a module that is mixed into a couple of classes but don't quite know how to go about it:
Do I test the instance methods by writing tests in one of the test files for a class that includes them (doesn't seem right) or can you somehow keep the tests for the included methods in a separate file specific to the module?
The same question applies to the class methods.
Should I have a separate test file for each of the classes in the module like normal rails models do, or do they live in the general module test file, if that exists?
We can run all of our tests at once by using the bin/rails test command. Or we can run a single test file by passing the bin/rails test command the filename containing the test cases.
To call a module method, you specify the name of the module, and the name of the method, separated by a dot. Like this: MyModule. my_method. But you can also include modules into classes so that those classes inherit all the module's instance methods.
IMHO, you should be doing functional test coverage that will cover all uses of the module, and then test it in isolation in a unit test:
setup do @object = Object.new @object.extend(Greeter) end should "greet person" do @object.stubs(:format).returns("Hello {{NAME}}") assert_equal "Hello World", @object.greet("World") end should "greet person in pirate" do @object.stubs(:format).returns("Avast {{NAME}} lad!") assert_equal "Avast Jim lad!", @object.greet("Jim") end
If your unit tests are good, you should be able to just smoke test the functionality in the modules it is mixed into.
Write a test helper, that asserts the correct behaviour, then use that against each class it's mixed in. Usage would be as follows:
setup do @object = FooClass.new end should_act_as_greeter
If your unit tests are good, this can be a simple smoke test of the expected behavior, checking the right delegates are called etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With