【问题标题】:DRY-ify RSpec testsDRY-ify RSpec 测试
【发布时间】:2012-08-30 10:23:58
【问题描述】:

我花了一个晚上的大部分时间阅读有关 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

有没有办法重构它来清理它?我想在其中添加多个有效值(目前仅根据长度检查该值),并对多个其他地址行变量执行相同的测试集。效率、可读性和可维护性对我来说都很重要,因此任何关于如何更好地进行此类测试的建议或任何推荐的阅读材料都将不胜感激。

【问题讨论】:

    标签: ruby-on-rails-3 rspec


    【解决方案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
    

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

    它允许编写如下测试:

    it {should ensure_length_of(:attribute).is_at_least(n).is_at_most(n)}
    

    【讨论】:

    • 这颗宝石应该可以节省大量时间,谢谢。这些例子也很有帮助。
    猜你喜欢
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 2011-06-09
    • 2021-09-26
    相关资源
    最近更新 更多