Skip to content

Instantly share code, notes, and snippets.

@bluerabbit
Last active January 13, 2021 04:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluerabbit/e531156a9cefb5c2c6ce3a2f00e62b8d to your computer and use it in GitHub Desktop.
Save bluerabbit/e531156a9cefb5c2c6ce3a2f00e62b8d to your computer and use it in GitHub Desktop.
rspecはシンプルなスタイルを好んだ方が読みやすいことが多い
# gem install rspec
# rspec calculator.rb
require "rspec"
class Calculator
def sum(value1, value2)
value1 + value2
end
end
# できるだけrspecの機能を使った複雑なスタイル
describe Calculator do
let(:calculator) { described_class.new }
describe "#sum" do
subject { calculator.sum(value1, value2) }
shared_examples_for "計算結果を検証する" do
it { expect(subject).to eq(answer) }
end
context "第一引数と第二引数がどちらも正の数の場合" do
let(:value1) { 1 }
let(:value2) { 2 }
let(:answer) { 3 }
it_behaves_like '計算結果を検証する'
end
context "第一引数は正の数で第二引数は負の数の場合" do
let(:value1) { 1 }
let(:value2) { -1 }
let(:answer) { 0 }
it_behaves_like '計算結果を検証する'
end
end
end
describe "Calculator: よくある複雑なスタイル" do
describe "#sum" do
subject { Calculator.new.sum(value1, value2) }
context "第一引数と第二引数がどちらも正の数の場合" do
let(:value1) { 1 }
let(:value2) { 2 }
it "正の数と正の数で計算した結果が取得できる" do
expect(subject).to eq(3)
end
end
context "第一引数は正の数で第二引数は負の数の場合" do
let(:value1) { 1 }
let(:value2) { -1 }
it "正の数と負の数同士でも計算できる" do
expect(subject).to eq(0)
end
end
end
end
describe "Calculator:シンプルなスタイル" do
describe "#sum" do
it do
expect(Calculator.new.sum(1, 2)).to eq(3)
expect(Calculator.new.sum(1, -1)).to eq(0)
end
end
end
@bluerabbit
Copy link
Author

rspecの高機能さに惑わされないでください。

rspecの機能を多く知っていて使いこなせるのがいい訳じゃないことがわかると思います。

    it do
      expect(Calculator.new.sum(1, 2)).to eq(3)
      expect(Calculator.new.sum(1, -1)).to eq(0)
    end

これだけで十分説明が済むものを多くの機能を使って表現する必要はありません。スタート地点はココからです。

多くの人が最初に下記のスタイルで書いてしまいがちです。

describe "Calculator: よくある複雑なスタイル" do
  describe "#sum" do
    subject { Calculator.new.sum(value1, value2) }

    context "第一引数と第二引数がどちらも正の数の場合" do
      let(:value1) { 1 }
      let(:value2) { 2 }
      it "正の数と正の数で計算した結果が取得できる" do
        expect(subject).to eq(3)
      end
    end

    context "第一引数は正の数で第二引数は負の数の場合" do
      let(:value1) { 1 }
      let(:value2) { -1 }
      it "正の数と負の数同士でも計算できる" do
        expect(subject).to eq(0)
      end
    end
  end
end
  • rspecの機能を使いこなすことに注力するのではなく読みやすいかに注力しましょう。
  • rspecの機能を知らない人でも読めるような学習コストが低い状態にするのも大事です。
  • いきなりテストの構造化やrspecのスタイルから入るのではなくitから書き始めましょう。

参考URL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment