2012年5月2日水曜日

API:jsonをテストする〜Rspec〜

前に作ったAPIのテストを作ってなかったのでそこのテストを作ります。
テストはRspecを使うのでまずは「test」フォルダを削除します。
次にGemfileを変更します。

Gemfile
group :development, :test do
  gem 'thin', :platforms => :ruby
  gem 'annotate', :git => 'git://github.com/ctran/annotate_models.git'

  gem 'rspec-rails'
  gem 'launchy'
  gem 'capybara'
  gem 'database_cleaner'
  gem 'factory_girl_rails', '~> 1.7.0'
end

thinはwindowsだと動かないのでdevelopmentだけにしました。
annotateはmodelにdbの内容を書き出してくれる便利なやつです。
さぁこれで準備OK!あとはコマンドでRspecの準備をします。

$ bundle install
もともとインストールあるので今回はやってませんが通常は以下の手順で行います。
$ gem install rspec
$ rails g rspec:install
      create  .rspec
      create  spec
      create  spec/spec_helper.rb

これでrspecフォルダが出来ました。 次にspecフォルダの下に「support」フォルダを作成し「integrration_test_helper.rb」を作成し以下の内容にします。
module IntegrationTestHelper
  def debug
    save_and_open_page
  end

  def dump
    puts page.body
  end
end
まずはテスト用データベースを作成します。
FactoryGirl.define do
  factory :announcement do
    sequence(:subject) { |n| "タイトル%02d" % n }
    sequence(:content) { |n| "お知らせ本文内容%02d" % n }
  end
end
作成方法は「FactoryGirl」で行います。spec下に「factories」フォルダを作成します。
そしてその下に「announcements.rb」を以下の様に作成します。

今回テストするのはコントローラーなので「controllers/api」フォルダを作ります。
そして中にannouncements_controller_spec.rbを以下の様に作成します。
# encoding: utf-8

require 'spec_helper'

describe Api::AnnouncementsController do
  render_views

  include IntegrationTestHelper #テストヘルパーを呼んでいます
  let(:announcement) { FactoryGirl.create(:announcement) }
   # FactoryGirlの情報をここに持ってきます。

  before do
    announcement
  end

  describe "#index (json)" do
    it "jsonデータを返す" do
      get :index, :format => "json"
      arr = JSON.parse(response.body)
    # 一度arrに入れてruby型式にしてjsonは配列で、かつ配列が1つだけなので
    [0]としてshouldで表示させます。

      arr[0]["id"].should == announcement.id
      arr[0]["subject"].should == announcement.subject
      arr[0]["content"].should == announcement.content
    end
  end
end
これを通したいと思います。
$ rake db:test:prepare
$ rake spec

~/.rvm/rubies/ruby-1.9.3-p0/bin/ruby -S rspec ./spec/controllers/api/announcements_controller_spec.rb
.

Finished in 0.25023 seconds
1 example, 0 failures

無事に通りました。「arr」に一度「JSON.parse(responce.body)」で代入することが重要ポイントの様ですね。

0 件のコメント:

コメントを投稿