0

私は夜のほとんどを RSpec に関するさまざまな記事やウォークスルーを読んで過ごしました。私は多くのことを学びましたが、物事を DRY のまま有用なものに保つことについては、まだ頭を悩ませています。RSpec が表現力豊かであることは素晴らしいことですが、初心者が簡潔なテストを書くのは難しいようです。

私がよく行っていることの 1 つは、各エッジ ケースの両側と、1 つの変数に対して 1 つまたは複数の有効な値をテストすることです。現時点では、私はそのようなことのために次のものを持っています:

context "when physical address line 1 is too short" do
  before { @contact.physical_addr_line_1 = "1" }

  it { should_not be_valid }
  specify { @contact.save.should_not be_true }
end

context "when physical address line 1 is too long" do
  before { @contact.physical_addr_line_1 = "1"*111 }

  it { should_not be_valid }
  specify { @contact.save.should_not be_true }
end

context "when physical address line 1 is valid length" do
  before { @contact.physical_addr_line_1 = "11111" }

  it { should be_valid }
  specify { @contact.save.should be_true }
end

それを少しきれいにするためにリファクタリングする方法はありますか?そこに複数の有効な値を追加し (現在はその値の長さに基づいてのみチェックしています)、他の複数の住所行変数に対して同じ一連のテストを実行したいと考えています。効率性、可読性、および保守性はすべて私にとって重要です。そのため、この種のテストや推奨される読書へのより良いアプローチ方法についての提案をいただければ幸いです。

4

1 に答える 1

0

このように少し乾かすことができます。また、読みやすくすると思います。

before ブロックで有効な属性を 1 回定義します。

before(:each) do
  @attr = #attributes hash
end

context "validations" do

  it "should not accept attribute that is too long" do
     long_string = "a" * unacceptable number
     Model.new(@attr.merge(attribute: long_string)).should_not be_valid
  end

  it "should not accept attribute that is too short" do
     short_string = "a" * unacceptable number
     Model.new(@attr.merge(attribute: short_string)).should_not be_valid
  end
end

また、shoulda gem も優れています。https://github.com/thoughtbot/shoulda

次のようなテストを書くことができます:

it {should ensure_length_of(:attribute).is_at_least(n).is_at_most(n)}
于 2012-08-30T11:33:30.830 に答える