PerlerのRuby日記

Rubyとか

親メソッドのテスト

よくわからなくなったのでメモ。



メソッドを作ったのでテストを書く。

class H
  def hoge(flag)
    if flag
      "hogehoge"
    else
      "hoge"
    end
  end
end
describe H do
  describe "#hoge" do
    subject{ H.new.hoge(flag) }
    context "when flag is true" do
      let(:flag){ true }
      it{ should eq "hogehoge" }
    end
    context "when flag is false" do
      let(:flag){ false }
      it{ should eq "hoge" }
    end
  end
end


この後、このH#hogeを呼び出すメソッドを作ったときにそのメソッドのテストは、hogeのflagにまで言及すべきなのだろうか。

class H
  def hoge(flag)
    if flag
      "hogehoge"
    else
      "hoge"
    end
  end

  def h(flag)
    [hoge(flag)]
  end
end
describe H do
  describe "#hoge" do
    subject{ H.new.hoge(flag) }
    context "when flag is true" do
      let(:flag){ true }
      it{ should eq "hogehoge" }
    end
    context "when flag is false" do
      let(:flag){ false }
      it{ should eq "hoge" }
    end
  end

  describe "#h" do
    subject(:h){ H.new }

    # このcontextは必要?
    context "when flag is true" do
      let(:flag){ true }
      specify{ expect(h.h(flag)).to eq ["hogehoge"] }
    end
  end

  describe "#h" do
    # それとも#hogeはもうテストしているから、もっと単純なテストの方がよいのか?
    subject(:h){ H.new.new(flag) }
    let(:flag){ true }
    it{ should eq [hoge(flag)] } # そのままhoge()を呼んでいる
  end
end


[hoge(flag)]で動的に期待値を出しているのは強引な感じがするけど、
このあとhogeメソッドの挙動が変わったときに、hの方のテストの修正までするのはちょっと面倒くさい。

hogeの方のテストでカバレッジは網羅できていて、hの方のテストでtrue/falseを試す必要があるのかどうか悩む。

単項演算子メモ

メモ。
Rubyには単項演算子が3つある。+と-と~だ。
ただし、これらは二項演算子と明確に区別されるので、オーバーライドするときには記号に@をつけて定義する。

class Fixnum
  def -@
    -2 * self
  end
end

i = 5
puts -i #=> -10

ちなみに、左辺に値が存在しない場合はいつまでも単項演算子なので、

i = 5
puts --i #=> 5
puts ++i #=> 5
puts -------------------i #=> 5
puts +++++++++++++++++++i #=> 5
puts -+-+-+-+-+-+-+-+-+-i #=> 5

なんてこともできる。なんだこれ。

なんか既視感あったと思ったら、これだった。

参考:
http://docs.ruby-lang.org/ja/2.1.0/doc/spec=2fdef.html#operator
http://docs.ruby-lang.org/ja/2.1.0/doc/symref.html