LoginSignup
1
1

More than 5 years have passed since last update.

Rspecのあれこれ1

Posted at

Rspecでわかったことをまとめます。(理解できていない点も含めて記載しておく。)その1です。

Rspecってこういうの

user.rb
class User
  validates :name, presence: true

  def repeat_user
    if user.use_count > 0
    return true
  end
spec/user_spec.rb
require 'spec_helper'

describe User do
  let(:user) { User.new(name: "pi----yo", email: "piyo@hoge.com", use_count: 2) }

  describe 'validations' do
    it "name", :aggregate_failures do
      user.name = "piyopiyo"
      expect(user).to be_valid
      user.name = ""
      expect(user).to be_invalid
    end
  end

  describe '#repeat_user' do
    it '二回以上購入(リピートユーザー)ならtrueが返る' do
      expect(user.repeat_user).to be true
    end

    it '一度も購入していない場合は falseが返る' do
      user.use_count = 0
      expect(user.repeat_user).to be false
    end
  end
end

キーワード

  • describe 〜についてテストするよと明示する。 '#repeat_user'のように書くと、 インスタンスメソッドのrepeat_userメソッドをテストしますという意味。
  • let インスタンス変数のように使える。 let(:user){.....}と記述すると、{.....}内の値を user として参照できるようになる。値の書き換えも可能。
  • aggregate_failures 特定のエクスペクテーション群をまとめて検証する。これを使用しないと、群の中でエラーになった部分までしかテストの実行がされないため、1個ずつ直して再度回す...というような作業を繰り返すことになる。
     
      ※エクスペクテーション => expect(X).to eq Y で記述する 期待値と実際の値の比較 部分のこと。

  • expect 値の比較を行う。

  • before do ... end example の実行前に毎回呼ばれる。 ブロックの中では、テストを実行する前の共通処理やデータのセットアップ等を行う。

これから調べたいこと

  • subject の使い方 => ちょろっと見たけど使用してみてまとめたい
  •  Factory_botやFabricationを使用したテストデータ生成周り                      ※ Fabricationはmongoidのembeded_manyに対応しているテストデータジェネレータ
1
1
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
1
1