LoginSignup
17
18

More than 5 years have passed since last update.

Rails/konachaでJavaScriptのテスト環境とCI環境を作ってTravisに載せた

Last updated at Posted at 2013-03-21

fastladderのリポジトリにJavaScriptのテスト環境を足してみた。その作業ログ。

具体的には以下の二つのコミット参照
https://github.com/fastladder/fastladder/pull/66/files
https://github.com/fastladder/fastladder/pull/85/files

後この記事
http://qiita.com/items/861f913b0f57203420d6

利点

  • mocha/chaiによるモダンなJSテスト環境
  • テスト側でも依存解決にsprockets利用可
  • 導入が簡単

欠点

  • ヘッドレス環境でCI統合がちょっとめんどい
  • javascript処理系が必要なのでJSエンジンが必要(PureなCentOSとかだとtherubyracerが必要)

導入

Gemfileに以下のものを追加する

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

sinon-railsはJSのモックライブラリ。なくてもいいけど、rspec書く人は入れたほうがいいと思う。

とりあえず一件だけテストを書く。
spec/javascripts/array_extra_spec.js

//= require application
//= sinon
describe("Array", function(){
  describe("#map", function(){
    it("return function applied array", function() {
      var arr = [1,2,3];
      var twice = function(i){return i*2;};
      expect(arr.map(twice)).deep.equal([2,4,6]);
    });
  });
});

Runnerを起動

bundle exec rake konacha:serve

http://localhost:3500 を開くとテストが実行される。

CI環境

poltergeistでヘッドレス実行できるようにする。
config/initializers/konacha.rb

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

WebMockがそのままだpoltergeistの邪魔をするのでlocalhostへの接続を許可する
config/environments /test.rb

+require 'webmock/rspec'
 Fastladder::Application.configure do
   # Settings specified here will take precedence over those in config/application.rb

   (...)

   # Print deprecation notices to the stderr
   config.active_support.deprecation = :stderr
+  WebMock.disable_net_connect!(:allow_localhost => true)
 end
+
+require 'webmock/rspec'
+WebMock.disable_net_connect!(:allow_localhost => true) 

実行

bundle exec rake konacha:run

productionのprecompile後に落ちる場合はコンパイル対象を列挙する
config/environments/production.rb の例

  +config.assets.precompile += %w( reader.js share.js subscribe.js)

Travis

travis.ymlのサンプル

rvm:
- 1.9.3
- 2.0.0
branches:
  only:
    - master
before_script:
  - 'cp config/database.yml.sqlite3 config/database.yml'
  - 'RAILS_ENV=test bundle exec rake setup'
  - "export DISPLAY=:99.0"
  - "sh -e /etc/init.d/xvfb start"
script: 'RAILS_ENV=test bundle exec rake db:drop db:create db:migrate spec konacha:run && RAILS_ENV=production bundle exec rake assets:precompile '
17
18
2

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
17
18