LoginSignup
45
45

More than 5 years have passed since last update.

Rails 3.2 のプロジェクトに jasmine 導入して CoffeeScript でテスト書くまで

Last updated at Posted at 2012-08-29

(evergreen gem を使ったより簡単な方法を http://qiita.com/items/077d4bbe12adb22c7637 に書いています)

Rails プロジェクトで使用する JavaScript / CoffeeScript をテストするため、jasmine を導入する。

jasmine gem 導入

# Gemfile
gem "jasmine"
bundle
rails g jasmine:install
rails g jasmine:examples
rake jasmine
# Open browser
open http://localhost:8888/

rails g jasmine:examples で生成したスクリプトは削除してよい。

spec の書き方

ここでは coffeescript で書いてるので後述の「spec を coffeescript で書く」参照。

describe "true", ->
  it "should be truthy", ->
    # shouldBeTruthy はメソッドなので最後の () は省略不可
    expect(true).toBeTruthy()

matcher の一覧

jasmine-jquery 導入

jasmine のみだと dom の絡む機能のテストを書く際に、createElement などでせっせと dom ツリーを作らないといけないし、関連するマッチャも用意しないといけない。

そのへんを省力化するためのツールが jasmine-jquery。

https://github.com/velesin/jasmine-jquery/downloads から jasmine-jquery-1.3.1.js をダウンロード、spec/javascripts/helpers へコピー。

追加される matcher

fixture

spec/javascripts/fixtures 下に html ファイルを作成する (内容は HTML フラグメント)。

test 中では loadFixtures(ファイル名); でページ中のフィクスチャ用コンテナ内にロードされる (ので fixture の要素には id つけとくべき)。

フィクスチャ用コンテナはテストごとに再作成される。

その他の関数

  • appendLoadFixtures(ファイル名, …): フィクスチャコンテナに追加
  • readFixtures(ファイル名, …): フィクスチャの内容を文字列で返す
  • setFixtures(html): 文字列か jQuery エレメントでフィクスチャコンテナの内容を置き換え
  • appendSetFixtures(html): 文字列か jQuery エレメントでフィクスチャコンテナの内容を追加
  • sandbox({attributeName: value, …}): div エレメントの作成、id がなければ sandbox になる。

spec を coffeescript で書く

app/assets 下などは rails がコンパイルしてくれるので気にしなくてよいが、spec は自前でコンパイルする必要がある。

# Gemfile
gem "guard-coffeescript"
bundle
# Guardfile なければ
guard init
# guard init coffeescript してもいいけどどうせすぐ書き換える
# Guardfile
guard "coffeescript", output: "spec/javascripts/compiled" do
  watch(%r{^spec/javascripts/(.*).coffee})
end

livereload

テスト書き換えるたび手動でブラウザリロードするのはめんどくさいので guard-livereload で自動化する。

# Gemfile
gem "guard-livereload"
bundle
guard init livereload

.coffee はチェックせず .js のみチェックすることで、コンパイル後のタイミングでリロードする。

# Guardfile
guard 'livereload' do
  # 下記の 1 行を追加
  watch(%r{spec/javascripts/.+\.js})
end

ブラウザの extension は https://github.com/mockko/livereload/blob/master/README-old.md から。

45
45
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
45
45