個人的にぱっと見て挙動が予想しやすいのは3。
1は何が起こるか分からない。
2も理解するのに時間がかかる。
4は短く書けるけど、書き手の意図がわかりにくい。
require 'rspec'
require 'active_support/core_ext/string'
describe "convert hash value to integer if the value is not '80'" do
let(:hash) { {to_exclude: '80', to_include1: '8080', to_include2: '3000'} }
shared_examples_for 'samples' do
specify { subject.call(:to_include1).should == 8080 }
specify { subject.call(:to_include2).should == 3000 }
specify { subject.call(:to_exclude).should be_nil }
specify { subject.call(:not_defined).should be_nil }
end
describe '1. use unless/or' do
it_should_behave_like 'samples' do
subject { ->(key) { hash[key].to_i unless hash[key].blank? or hash[key] == '80' } }
end
end
describe '2. use if/not/or' do
it_should_behave_like 'samples' do
subject { ->(key) { hash[key].to_i if not(hash[key].blank? or hash[key] == '80') } }
end
end
describe '3. use if/and' do
it_should_behave_like 'samples' do
subject { ->(key) { hash[key].to_i if hash[key].present? and hash[key] != '80' } }
end
end
describe '4. use unless/include?' do
it_should_behave_like 'samples' do
subject { ->(key) { hash[key].to_i unless [nil, '80'].include? hash[key] } }
end
end
end
$ rspec sample_spec.rb
................
Finished in 0.004 seconds
16 examples, 0 failures
え?そもそもこのRSpecがわかりにくい?