0

我花了一个晚上的大部分时间阅读有关 RSpec 的各种文章和演练。虽然我学到了很多东西,但我仍然对保持干燥和有用的东西有点不知所措。RSpec 的表现力很棒,但它似乎让初学者难以编写简洁的测试。

我可以看到自己经常做的一件事是测试每个边缘情况的两侧,以及单个变量的单个或多个有效值。目前,我对这样的事情有以下几点:

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 块中定义一次有效属性:

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

此外,shouda gem 非常棒。https://github.com/thoughtbot/should

它将允许编写如下测试:

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