We use the Mocha testing framework.
- The
setup
method gets called before each test. - Set up
@instance_variable
in setup, and use it in tests.
- This is the most basic form of testing.
assert
,assert_not
,assert_difference
,assert_nil
, etc.- DRY is good, but don't go crazy with loops to eliminate all duplication.
- Tests should be easy to read.
- Another style that some frameworks use is
object.should.be.true
, and things like that. - Yet another style:
expect(object).to_be(true)
. Note that this is not related to the "Expectations" section.
- Fixtures are test data stored in a YAML file.
- You access instances with
class_name(:handle)
. - They are real ActiveRecord objects, but it's better this way because you are not testing the model at the same time.
- A stub provides a basic implementation of a method.
- We are testing something that we know will use a certain method, so we stub that implementation to avoid having to do complicated setup to make that work.
- We talk about "stubbing out" a method.
- An expectation is just like a stub, except we expect it to be called exactly one (or a different number of times).
- Stubs are tools for testing, but expectations are also tests in themselves since they require the implementation to use the stubbed methods.
- Expectations are automatically verified at the end of the test.
- A mock is a object that pretends to be something bigger.
- Think of it as a stunt double.
- You can mock a class by creating a much simpler one, faking the behaviour by simply returning specific values.
- Automated mocking works like
obj = mock('object')
. - You can then stub or expect the mock object and assert things about its behaviour.
- Mocha allows you to do
Class.any_instance.stub(...)
, which in many cases is easier than creating mock objects. - That is also known as partial mocking.
- You can access the instance variables of the object you're testing using
assigns(:variable_name)
. - This can be useful for things that are otherwise hard to test.
- Dummy: object passed around but never used; a trivial placeholder (
nil
orObject.new
) with no behaviour relevant to the test. - Fake: has a working implementation, but makes shortcuts (such as in-memory database); unsuitable for production.
- Stub: provides canned answers to calls made during tests, and possibly lacking implementations for unneeded methods.
- Spy: records method invocations, and the test makes assertions about them after.
- Mocks: pre-programmed with expectations of the method calls it is to receive, and verifies them itself at the end.
- Expect commands, stub queries.
- Wrap external services in an adaptor, then mock the adaptor.
- Mock roles, not objects.