yo_waka's blog

418 I'm a teapot

RailsアプリのJavaScriptをkonachaを使ってCLI上でテストする

前回のでアプリケーションのテストがMiniTest::Specで実行できるようになったので、今度はJavaScriptユニットテストをコマンドラインから実行できるようにする。

慣れてるMochaを使ってテストが書けるkonachaと、konachaが使用するCapybaraのPhantomJSドライバであるpoltergeistを使う。

Gemfile

group :test do
  gem 'konacha'
  gem 'poltergeist'
end

konachaの設定はinitializerで。
ドライバをpoltergeistにして、テスト対象ディレクトリを"test/javascripts"に変えた(デフォルトは"spec/javascripts")。

config/initializers/konacha.rb

if defined?(Konacha)
  Konacha.configure do |config|
    require 'capybara/poltergeist'
    config.driver = :poltergeist
    config.spec_dir = "test/javascripts"
  end
end

mochaの設定はテストディレクトリ直下にspec_helper.jsを置いてその中に書くらしい。

test/javascripts/spec_helper.js

// set the Mocha test interface
// see http://visionmedia.github.com/mocha/#interfaces
mocha.ui('bdd');

// ignore the following globals during leak detection
mocha.globals(['util']);

// or, ignore all leaks
mocha.ignoreLeaks();

// set slow test timeout in ms
mocha.timeout(5);

テストディレクトリ以下にある、"hoge_test.js"あるいは"hoge_spec.js"というファイルがテストファイルとなる。 もちろんSprokectsを使ってRailsのasset pipelineを使ってテストしたいJSファイルを読み込むことができる。
precompile済みならapplication.jsを指定するくらいか。

//= require spec_helper
//= require application

あとはchaiアサーションを使ってテストを書いてkonacha:runすればphantomjsでテストが実行される!

RAILS_ENV=test bundle exec rake konacha:run