RSpec 3.1を使ってみたよヘ(^o^)ノ

さて、RSpec3.1がリリースされたので早速新機能をつかってみました。

Warnings flag

.rspecファイルから--warningsがいなくなりました。

# .rspec
--color
--require spec_helper

warningsを表示したい場合↓

# spec_helper.rb
RSpec.configure do |config|
  config.warnings = true
end

have_attributes

データをチェックするテストが簡単に書けるようになったね。

require 'spec_helper'

describe 'have_attributes' do
  User = Struct.new(:name)

  specify 'nameはmurajun1978であること' do
    user = User.new('murajun1978')
    expect(user).to have_attributes(name: 'murajun1978')
  end

  specify 'murajun1978とmurajunのユーザが存在すること' do
    users = [User.new('murajun1978'), User.new('murajun')]
    expect(users).to match_array [
      an_object_having_attributes(name: 'murajun1978'),
      an_object_having_attributes(name: 'murajun')
    ]
  end
end

define_negated_matcher

反転まっちゃーを定義できるようになりました

describe 'negated_matcher' do
  let(:array) { ['murajun1978'] }

  specify 'murajun1978が含まれていること' do
    expect(array).to include 'murajun1978'
  end

  specify 'murajunが含まれていないこと' do
    expect(array).to exclude 'murajun'
  end
end

これを実行するとundefined method `exclude'と怒られます

spec_helperに定義してみましょう

RSpec::Matchers.define_negated_matcher :exclude, :include

再度実行するとパスします。

ちなみに今までの書き方はこう

describe 'negated_matcher' do
  let(:array) { ['murajun1978'] }

  specify 'murajunが含まれていないこと' do
    expect(array).to_not include 'murajun'
  end
end

custom matcher DSLでchainが使える

RSpec::Matchers.define :be_smaller_than do |max|
  chain :and_bigger_than do |min|
    @min = min
  end

  match do |actual|
    actual < max && actual > @min
  end
end

expect(10).to be_smaller_than(20).and_bigger_than(5)

ぐーんとテストが書きやすくなった感じですねー

Greatです٩( ‘ω’ )و

参考サイト

Myron Marston » RSpec 3.1 has been released!