HABTM Unit Testing in CakePHP

I use this blog quite a bit for documenting little quirks, bugs, work-arounds, neat things, and tutorials so that I know where I can find the solution in the future. At the same time, you benefit by hopefully not having to go through some of the same messes I did just to get to this point.

I love CakePHP so far (but still quite the noob), but my biggest gripe is the documentation. The basics are there, but there’s often too little documentation to get the novice going. From the Bakery docs, it’s not exactly clear how to perform tests on models when HABTM (has and belongs to many) relationships are involved. Have no fear, it’s doable (though not straightforward).

Hopefully you baked your MVC pieces and included test scripts to go along with them. If not, do that first. The key part to getting the tests for models that have HABTM relationships is to set-up a fixture representing the table that stores the relationship. Don’t actually set-up the test – just the fixture.




3 Comments

Hi,

I’m trying to set up fixtures for HABTM unit testing, but wasn’t able to get it to import from my database. Do you have any suggestions or example code?

Thanks!

I’ve always had issues trying to get testing/fixtures to grab the data I want it to. Call it a struggle. Personally, I prefer writing the actual fixture into the flat file because I can control what garbage gets sucked in there and that in turn becomes predictable data rather than tables that might be somewhat broken if I’m developing other parts of the app in parallel. Keep playing with it and just make sure all the proper linking looks like it should work. Also – don’t hesitate to hit up the IRC chat room. The folks there are usually pretty helpful if you’re patient enough and thorough enough to make it look like you’ve at least tried on your own.

It definitely makes sense to write the actual fixture instead of importing. I will definitely check out the IRC chat room in the future. Thanks for all of your help!

Leave a Reply