RailsでMondoid使用時のユニットテスト

注) ここではモデルのテストについてのみ記載する。

Gemfileに追記

gem 'mongoid-fixture_set'


インストール

bundle install --path vendor/bundle


テストデータの準備

例) test/fixtures/books.yml

one:
  name: "book1"
  price: 1008
  note: "note1"

two:
  name: "book2"
  price: 2016
  note: "note2"


テストクラスの記述

require 'test_helper'

class BookTest < ActiveSupport::TestCase

  # この2行を追記(コントローラのテストの場合も同様)
  include Mongoid::FixtureSet::TestHelper
  self.fixture_path = "#{Rails.root}/test/fixtures"

  #----------------------------
  # 初期処理
  #----------------------------
  def setup
    @book1 = books(:one)
  end 

  #----------------------------
  # テストを記述
  #----------------------------
  test "test1" do
    cnt = Book.where(name:"book1").count
    assert_equal 1, cnt, "検索結果件数が期待値と異なります"
    books = Book.where(name:"book1")
    assert_equal @book1.name , books[0].name  , "name  が期待値と異なります"
    assert_equal @book1.price, books[0].price , "price が期待値と異なります"
  end 

end


テストの実行

$ rake test:models TEST="test/models/book_test.rb"

Run options: --seed 38317

# Running:

.

Finished in 0.034300s, 29.1543 runs/s, 87.4630 assertions/s.

1 runs, 3 assertions, 0 failures, 0 errors, 0 skips

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2016-05-08 (日) 03:11:30 (3183d)