RSpec の入門とその一歩先へを Rspec3でやってみた

RSpec の入門とその一歩先へをやってみたがRSpecのバージョンが低かったのでRSpec3使って書きなおしてみました.

書きなおしたのはイテレーション3の仕上げに乗っているコードです.

message_filter_spec.rb(変更後)

require 'bundler'
require './message_filter'

describe MessageFilter do
  share_examples_for 'MessageFilter with argument "foo"' do
    it { is_expected.to be_detect('hello form foo') }
    it { is_expected.not_to be_detect('hello world') }
    it { expect(subject.ng_words).not_to be_empty }
  end

  context 'with argument "foo"' do
    subject { MessageFilter.new('foo') }
    it_should_behave_like 'MessageFilter with argument "foo"'
    it { expect(subject.ng_words.count).to eq 1 }
  end

  context 'with argument "foo","bar"' do
    subject { MessageFilter.new('foo', 'bar')}
    it_should_behave_like 'MessageFilter with argument "foo"'
    it { is_expected.to be_detect('hello from bar') }
    it { expect(subject.ng_words.count).to eq 2 }
  end
end

requireは自分の環境に合わせてやってください.

僕はbundler使ってるのでこうなっているだけです.

まずはit { should }ワンライナーを書き換えました. shouldの代わりにis_expected.toを使うらしい(RSpecの最新の動向・RSpec 3へのアップグレードガイド).

it { should be_detect('hello from foo') } # 変更前
it { is_expected.to be_detect('hello form foo') } # 変更後

次にsubjectを使っているのでit { @message.should }it { should }とかけたのですがexpectを使うとどうすればいいかよくわからず it { expect(subject)}としました.

it { expect(subject.ng_words.count).to eq 1 } # 変更前
it { should have(1).ng_words } # 変更後

また,RSpec3からitshaverspec-corerspec-expectationsから他のgemに移動したらしくそのままでは動かなかったので無理やり書き換えました(The Plan for RSpec3).

itsの変更はit使ってごまかした

its(:ng_words) { should_not be_empty } # 変更前
it { expect(subject.ng_words).not_to be_empty } # 変更後

haveは'count'のeqにしてごまかす

it { expect(subject.ng_words.count).to eq 1 } # 変更前
it { should have(1).ng_words } # 変更後

これであってのかな感が.