October 30, 2009 by alex
I just released Couch Potato 0.2.14 and amongst other things it has a new feature i think is pretty neat: you can unit test your (JavaScript) views using RSpec and Ruby.
You can declare a view in Couch Potato like this:
This will generate a pair of map/reduce function and push them to Couch Potato. The map function looks something like this:
[javascript] function(doc) { if(doc.ruby_class == ‘Comment’) { emit(doc.post_id, 1); } } [/javascript]
And here’s a unit test for that function:
As you can see all you have to do is pass a Ruby Hash that looks like your CouchDB document and the expected results. You can also pass in multiple results if you expect your map function to emit multiple key/value pairs.
Testing a reduce function works the same way:
For testing re-reducing you simply call .should rereduce(...).to(...)
.
So how come you can test JavaScript functions in pure Ruby? Well, by stealing other people’s tricks. I recently contributed a few patches to mustache.js which is a new templating library ported to JavaScript by @janl. It has a test runner currently implemented in Ruby which generates JavaScript code on the fly, runs it using Spidermonkey and reads back the results. I have added a few steps to this process:
You can see how it works by looking at the code for the RSpec matchers.
I think this addition lowers the barrier to test your views quite a bit. Although I’m usually not a big fan of “one language to rule them all” and love writing JavaScript, being able to write all the necessary tests in Ruby when working on a Ruby project makes things way easier.