classMember attr_accessor:rank definitialize(rank) @rank = rank end defbonus if@rank === 'silver' 0.9 elsif@rank === 'golden' 0.8 end end end RSpec.describe ".bonus method"do let(:member) { Member.new('normal') } it 'should feedback 10% discount when member is silver rank.'do member.rank = 'silver' expect(member.bonus).to eq(0.9) end it 'should feedback 20% discount when member is golden rank.'do member.rank = 'golden' expect(member.bonus).to eq(0.8) end end
結果:
1 2 3 4 5 6
.bonus method should feedback 10% discount when member is silver rank. should feedback 20% discount when member is golden rank. Finished in0.00202 seconds (files took 0.05494 seconds to load) 2 examples, 0 failures
RSpec.describe ".bonus method"do let(:member) { Member.new('normal') } context "when member is silver rank"do it 'should feedback 10% discount.'do member.rank = 'silver' expect(member.bonus).to eq(0.9) end end context "when member is golden rank"do it 'should feedback 20% discount.'do member.rank = 'golden' expect(member.bonus).to eq(0.8) end end end
結果:
1 2 3 4 5 6 7 8
.bonus method when member is silver rank should feedback 10% discount. when member is golden rank should feedback 20% discount. Finished in0.00194 seconds (files took 0.05754 seconds to load) 2 examples, 0 failures
如此一來,是不是變得很有結構,閱讀起來也容易很多!
在使用 context 時,要特別注意,慣例上都是以 when, with, without 作為開頭。
另外,context 也可以由 describe 代替:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
RSpec.describe ".bonus method"do let(:member) { Member.new('normal') } describe "when member is silver rank"do it 'should feedback 10% discount.'do member.rank = 'silver' expect(member.bonus).to eq(0.9) end end describe "when member is golden rank"do it 'should feedback 20% discount.'do member.rank = 'golden' expect(member.bonus).to eq(0.8) end end end