Fail! cakePHP 1.2 model testing with associations
January 20th, 2008 by ScottK | No Comments | Filed in cakePHPI love to unit test! All the way down to my JavaScript libraries you’ll find a unit test. While some may argue that Behavior Driven Development is better I find that that TDD not only affords me more robust bug free code but also ensures that I am not going off track during development. So with cakePHP 1.2 beta and simpleTest we get a unit test framework for making sure that the code we write is tested prior to production.
Very Cool as that is one judgement I use to determine if the language or framework I am working with will amount to anything, i.e. can it be tested. cakePHP can be tested with SimpleTest and you can load fixtures to make sure your tests are correctly setup for what you need to
However….
With the introductions of associations in cakePHP it fails miserably. Given that I have a model for a blog post I can write and use all the tests that I need to make sure that it performs exactly as I need it to do and handle all the foreseen exceptions. That was really cool until I added the comment model. The post model has many comments and the comment model belongs to a post. That’s where the problems begin.
The resulting unit test then began to throw exceptions in the tests where looking for test_suite_post_id in the comment table as opposed to post_id. What I mean is that in the comment model that belonged to a single post one field was post_id which was the foriegn key to the post so the model associations would work. In the testing environment however the tests where looking for a field called test_suite_post_id which didn’t exist.
I did find that if you import the database field representation with records => true you would not throw the errors and exceptions. Seriously though it’s using live data from your production database and you have no way to fine grain the exceptions to test your tests.
Certainly one could argue that the fixtures could implement the strange behavior as such but because the comment fixture test would only load the fixtures for the comment model and not multiple models, I would hope that post_comment fixtures file wouldn’t be necessary (I didn’t even try this) during the setup of the comment test. In this structure there would be a lot of files for testing one model as large sites development.
With cakePHP 1.2 beta we have been presented with a lot of goodness. Testing for associative models still needs some improvement however. I’m not sure if it’s cakePHP or the simpleTest platform for the failure but non-associative testing works just fine.
