views:

105

answers:

2

Besides the fact that Rails incorporates the database layer into the unit tests (which then is strictly not a unit test), what if I test for model interdependencies, e.g. check if has_many/belongs_to with :dependent => :destroy really destroys the associated items or items from join models to not leave orphans around?

Should such a test maybe better be placed in the function or integration tests?

Or asked another way: Is there a guide with examples which kind of tests should go where and why? I didn't find anything really useful.

A: 

A unit in a unit-test isnt always a single class or object. Testing interdependencies shouldn't be a problem. I havent found any hard and fast rules for defining units in unit tests but I often use ideas from domain driven design to guide me. Tests that test behaviour of a single aggregate are usually pretty maintainable as unit tests. Test that depend on more aggregates or even aggregates and services together are integration tests.

Mendelt
I figure out that I should probably take "unit testing" as "testing in a closed well defined environment" while "integration testing" may integrate external services I have no direct control over.
hurikhan77
+1  A: 

As a general rule of thumb models are unit tested, controllers are functionally tested and integration tests are done with views. If you're using RSpec you'll have model, controller and view specs - but essentially testing the same stuff.

You can always mock actions (with gems like Mocha or Flexmock) to avoid having calls to methods actually do anything - but you want to make sure the expected behavior is happening. (E.g. a call is made to MyClass.create or MyClass.destroy). It is especially true of controller/view tests where I often will mock a call to a model.

In my experience though I don't usually have problems with models and associations using the database. You might want to look at Factory Girl or some alternative to fixtures, which make it easier to manage test objects/data.

Nicholas C
+1 for the additional pointers
hurikhan77