rpsecによるリファクタリング

require 'calc'

RSpec.describe "A calc" do
  before do
    @calc = Calc.new
  end
  it "given 2 and 3, returns 5" do
    expect(@calc.add(2, 3)).to eq(5)
  end
  it "given 5 and 8, returns 13" do
    expect(@calc.add(5, 8)).to eq(13)
  end
end
class Calc
  def add(a, b)
    a + b # 仮実装
  end
end
[vagrant@localhost rspec]$ rspec
..

Finished in 0.00235 seconds (files took 0.11087 seconds to load)
2 examples, 0 failures

describeはcontextを書き換えることも可能。また、コマンドラインはrspec -fdとしても使われる。

pendding

require 'calc'

RSpec.describe Calc do
  describe "when normal mode" do
  it "given 2 and 3, returns 5" do
    calc = Cal.new
    expect(calc.add(2, 3)).to eq(5)
  end
  describe "when graph mode" do
  it "draws graph" do
  end
end

matcher:https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers

    expect(calc.add(2, 3)).to eq(5) #matcher
    expect(calc.add(2, 3)).not_to eq(5) #matcher
    expect(calc.add(2, 3)).to be true #matcher
    expect(calc.add(2, 3)).to be false #matcher
    expect(calc.add(2, 3)).to be > 10 #matcher
    expect(calc.add(2, 3)).to be_between(1, 10).include #matcher
    expect(calc).to respond_to(:add) #matcher
    expect(calc.add(2, 3).integer?).to be true

subject

require 'calc'

RSpec.describe Calc do
  subject(:calc){ Calc.new }
  it {
    # calc = Calc.new
    expect(calc.add(2, 3)).to eq(5)
  }
end

let

context "tax 5%" do
    let(:tax){ 0.05 }
    it { expect(calc.price(100, tax)).to eq(105)}
  end
  context "tax 8%" do
    let(:tax){ 0.08 }
    it { expect(calc.price(100, tax)).to eq(108)}
  end

message expectation

class Calc

  def initialize(logger)
    @logger = logger
  end

  def add(a, b)
    @logger.log
    a + b
  end

end