Fixrb

Fix 1ガイド

RSpecからの移行

同じ考え方を別の名前で。そして、意図して省いたいくつかのもの。

RSpecもFixも、入れ子のコンテキストと期待で振る舞いを記述します。根本で異なる点は2つです。Fixの仕様はクラスを名指ししません。サブジェクトは最後の行のテストから来るので、同じ仕様で別のサブジェクトもテストできます。そして仕様は文書で、ファイルの読み込み時に一度だけ読まれます。期待の前や後に実行されるコードはもちません。

構造

RSpecFix
RSpec.describe Counter do … endFix :Counter do … end
subject { Counter.new(start) }テストのブロック:Fix[:Counter].test { Counter.new(start) }
describe "#count"のあと、各exampleでsubject.counton :count do … end
let(:start) { 0 }let(:start) { 0 }。サブジェクトブロックとほかのletからだけ見える
let(:start) { 5 }をもつcontextwith start: 5 do … end
before { subject.increment }準備する期待を囲むon :increment do … end
it { is_expected.to eq(0) }it MUST eq 0
is_expected.not_toit MUST_NOT
shared_examples, it_behaves_like独立した仕様にしてfix(:Name)で求めるか、複数のサブジェクトに対してテストする
rspec, rspec spec/modelsfix, fix fix/models
rspec --order randomファイルの順序ならfix --random
rspec --seed 1234fix --random=1234

subjectをもち、あるコンテキストではbeforeでインクリメントし、別のコンテキストではletを上書きする、カウンターのRSpecのspecは、次のようになります。

require "fix"

class Counter
  attr_reader :count

  def initialize(start) = @count = start
  def increment = tap { @count += 1 }
end

Fix :Counter do
  let(:start) { 0 }

  on :count do
    it MUST eq 0
  end

  on :increment do
    on :count do
      it MUST eq 1
    end
  end

  with start: 5 do
    on :count do
      it MUST eq 5
    end
  end
end

exit(Fix[:Counter].test { Counter.new(start) })
ruby counter_fix.rb
counter_fix.rb:14: Success: expected 0 to eq 0
counter_fix.rb:19: Success: expected 1 to eq 1
counter_fix.rb:25: Success: expected 5 to eq 5

beforeは連鎖のメソッドになりました。incrementがカウンターを返し、そこにcountが送られます。連鎖を超える準備が必要なメソッドは、letを使ってサブジェクトブロックの中で準備します。

マッチャー

RSpecFix
eq(x), eql(x)eq(x)。xのクラスを求め、eql?を使います。RSpecのeqは==を使います。1.0はeq 1ではありません
equal(x), be(x)be(x)
be(true), be(false), be_nilbe_true, be_false, be_nil
be_truthy, be_falseysatisfy { |value| !!value }, satisfy { |value| !value }
be_a, be_kind_ofbe_a_kind_of
be_an_instance_of, be_instance_ofbe_an_instance_of
be_within(d).of(x)be_within(d).of(x)
match(regexp)match(regexp)。StringかSymbolに対して
satisfy { |v| … }, be >= 3satisfy { |v| … }。trueかfalseを答える
expect { … }.to raise_error(K)raise_exception(K)。例外を発生させるのはコンテキストのメソッド
expect { … }.to change { o.count }.by(1)change(o, :count).by(1)
be_emptyなどの述語on(:empty?) { it MUST be_true }
include(x), start_with(x)on(:include?, x) { it MUST be_true }, on(:start_with?, x) { … }
have_attributes(name: "Ada")on(:name) { it MUST eq "Ada" }、またはits(:name) { MUST eq "Ada" }
match_array, contain_exactlyon(:sort) { it MUST eq [1, 2, 3] }

pendingの代わりに3つのレベル

RSpecはexampleをスキップしたり、失敗しても実行全体が失敗しないようpendingをつけたりします。Fixはそれを仕様そのものの中で述べます。推奨されることにはSHOULDを使い、満たされなければWarningになります。任意のことにはMAYを使い、メソッドがなければInfoになります。どちらも成功として扱われ、どちらも行に書かれるので、何も隠れません。5つの判定は仕様を書くにあります。

意図して省いたもの

両方をひとつのプロジェクトに、それぞれのディレクトリで共存させることもできます。その方法はプロジェクトで使うにあります。