LoginSignup
11
10

More than 5 years have passed since last update.

Konachaの導入手順とheadlessテストで出力フォーマットを変更する方法

Last updated at Posted at 2013-08-08

KonachaはRailsでJavaScriptのテストフレームワークのMochaを使いやすくしてくれるやつです。
https://github.com/jfirebaugh/konacha

似たようなのでJasmineをRailsで使いやすくするEvergreenってのもあるけど、Konachaの方が開発が活発。

Konachaでheadlessテストしたときの出力フォーマットを変更する方法がぐぐってもあまり見つからなかったのでメモしておこうと思いました。ついでにせっかくだから導入手順から書いておきます。

Konacha等のgemのインストール

Gemfileに以下を追加して、bundle install

Gemfile
group :development, :test do
  gem 'konacha'
  gem 'poltergeist'
  gem 'chai-jquery-rails'
  gem 'sinon-rails'
end

poltergeistはheadlessブラウザを使うなら必要。
chai-jquery-railsはなくてもいい。アサーションを簡潔に書けるときがあるくらい。
sinon-railsはMockやStubを作れるライブラリ。なくてもいいけど、ajaxやconfirmのテストに便利。

Phantom.jsインストール

Macでhomebrewの場合は以下のコマンド。

$ brew install phantomjs

※それ以外の場合はこちらを見てください。

Phantom.jsはpoltergeistが使っているheadlessブラウザです。

Konachaの設定を変更

config/initializers/konacha.rbに以下の設定をする。

config/initializers/konacha.rb
Konacha.configure do |config|
  RSpec.configure do |c|
    c.color = true
  end
  require 'rspec/core/formatters/documentation_formatter'
  require 'capybara/poltergeist'
  config.driver = :poltergeist
  config.formatters = [RSpec::Core::Formatters::DocumentationFormatter.new(STDOUT)]
end if defined?(Konacha)

RSpecなんちゃらかんちゃらって書いてあるところが、この記事の本題の出力フォーマットの設定です。RSpecでも--format documentationを指定する派なので、合わせたかった。
RSpecの他のフォーマットも使えるけど、きっとDocumentationFormatter以外使わないでしょう。
デフォルトは味気ない成功するとドットが並ぶやつです。

konacha.rbの他の設定はpoltergeistを使う設定です。

もう一つ設定します。
spec/javascripts/spec_helper.js.coffeeを以下の内容で作成。

spec/javascripts/spec_helper.js.coffee
#= require application
#= require chai-jquery
#= require sinon

beforeEach ->
  @sandbox = sinon.sandbox.create()

afterEach ->
  @sandbox.restore()

各specごとに書いてもいいけど、面倒なのでspec_helperに書きます。

sandboxうんちゃらはMock作るSinon.JSの設定。毎回Mockをクリアしておきます。

テスト作成

適当にテストを作ります。CoffeeScriptじゃなくてJavaScriptでもいいです。

spec/javascripts/array_sum_spec.js.coffee
#= require spec_helper

describe "Array#sum", ->
  it "returns 0 when the Array is empty", ->
    expect([].sum()).to.equal(0)

  it "returns the sum of numeric elements", ->
    expect([1,2,3].sum()).to.equal(6)

実行

ブラウザで実行する

$ bundle exec rake konacha:serve

で、 http://localhost:3500 を開くと全テストが実行されます。

コマンドラインで実行する

$ bundle exec rake konacha:run

以下のようなフォーマットで出力されます。色ついてないですけど、色もつきます。


Array#sum
  returns 0 when the Array is empty
  returns the sum of numeric elements

Finished in 0.00032 seconds
2 examples, 0 failures

ちなみに上の出力フォーマットの設定をしないとこんな出力です。

..

Finished in 0.00 seconds
2 examples, 0 failed, 0 pending

入れるだけ入れてSinon.JSやchai-jquery-railsは使っていませんが、詳しくはドキュメントを見てください。

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10