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からits
とhave
がrspec-core
とrspec-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 } # 変更後
これであってのかな感が.