LoginSignup
2
2

More than 5 years have passed since last update.

RailsでKonachaとSinon.JSを合わせて使う

Last updated at Posted at 2013-02-28

KonachaだけでもJSテストをするには十分かもしれないが、Ajaxなどの通信部分のテストなどは面倒だ。
そこをSinon.JSを導入して解決する。

Sinon.JSとは?

公式。
http://sinonjs.org/

mixiのエンジニアブログに分かりやすい導入編が載っているので参考にしてください。
http://alpha.mixi.co.jp/2011/10798/

フェイクオブジェクトを作成することで、関数が呼ばれたかどうかを監視したり、ダミーのXHRやServerを作成することで、サーバ側の依存を無くしたりできます。
素晴らしいですね。

Railsに導入する

これ幸いなことに、Rails用のgemがあります。

Gemfile
gem 'konacha'
gem 'sinon-chai-rails'
gem 'sinon-rails'

bundle installしてください。

  • sinon-rails
    • Sinon.JSをRailsにインストールします
  • sinon-chai-rails
    • Sinon.JSとChaiをつなげるものらしい(あまり理解してない・・・)
    • KonachaはChaiが含まれているので念のため入れておきます

試しに使う

application_spec.js
//= require application
//= require sinon-chai
//= require sinon

var Hogeee = function(callback) {
  /* 中でXHR使っているとイメージしてください */
  /* 通信に成功したらcallbackを実行する */
}

describe("Hogeee", function(){
  it("通信に成功する", function(){
    var _xhr, _requests;
    beforeEach(function(){
      _xhr = sinon.useFakeXMLHttpRequest();
      _requests = [];
      _xhr.onCreate = function(xhr){
        _requests.push(xhr);
      }
    });
    afterEach(function(){
      _xhr.restore();
    });

    var spy = sinon.spy();
    Hogeee(spy);  // コールバック関数にspyを仕込む
    _requests[0].respond(200);  // sinonに200を返させる
    // calledWithMatchの中のオブジェクトとHogeeeのコールバック関数が同じかどうか
    spy.calledWithMatch({ data: '成功ですわ' }).should.be.ok;
  });
});

あとは適当に頑張れば幸せになれる。

2
2
1

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