If you don't use Ruby on Rails, don't worry; this article has very little Rails coverage in it. We're going to focus on using Mocha and Chai, as well as a few other libraries, to test our code. Since that's the case, you should be able to follow along.
To demonstrate testing some "real" code, including DOM interactions, AJAX requests, conditionals, and so on, we'll need some code. I've created a simple Todo List application and placed the source code, along with all of the tests we'll write, on GitHub.com, ready for you to download. After downloading the files, play with the code as you like.
In part 1 of this series, we set up the testing frameworks and even got a basic test to pass. Now we're going to be testing something more interesting than a simple Greeter class.
# Require the appropriate asset-pipeline files: #= require application #= require_tree ./support # Any other testing specific code here... # Custom matchers, etc.... Konacha.mochaOptions.ignoreLeaks = true beforeEach -> window.page = $("#konacha")
The spec_helper file will be required by all the test files we create, giving all of them access to a common set functionality and code.
Rails alert! This material is strictly related to Rails.
The support directory will hold any third-party scripts (or scripts we write) that are helpful to our tests, but not helpful to the main application.
End of Rails! That's it for the Rails stuff, folks.
The first interesting bit of code you'll notice is the following line:
Konacha.mochaOptions.ignoreLeaks = true
While it might look like an odd thing to do, I've set the ignoreLeaks option to true because it doesn't seem to like when I add properties to the window object, as I'm about to do in the next bit of code. This flag prevents a whole series of warnings and errors from being thrown.
beforeEach -> window.page = $("#konacha")
The Mocha library has beforeEach and afterEach hooks that will be executed at their respective times in the test lifecycle. For example, the beforeEach function we've defined here will be run before every test.
In this beforeEach function, I'm defining the window.page property to equal that of the DOM element $("#konacha"). What is this DOM element? It's inserted into the DOM by the Konacha gem to give tests a "playground" DOM. After each test, this element will be wiped clean (think database transactions for the DOM). I like to set it with the window.page property because I feel it makes my tests easier to read. Also, if the DOM element changes names later, I can change it in one place and not have to worry about it.