【问题标题】:How to DRY (these) RSpec tests using custom matcher如何使用自定义匹配器干燥(这些)RSpec 测试
【发布时间】:2012-01-14 05:00:45
【问题描述】:

我目前有以下测试,看起来适合进行一点 DRY 治疗:

describe League do

  context 'attributes validation' do
    before(:each) do
      @league = League.new
    end

    it 'should be invalid without a short_name' do
      @league.attributes = valid_league_attributes.except(:short_name)
      @league.should_not be_valid
      @league.should have(1).error_on(:short_name)
      @league.errors[:short_name].should == ["can't be blank"]
      @league.short_name = 'NFL'
      @league.should be_valid
    end

    it 'should be invalid without a long_name' do
      @league.attributes = valid_league_attributes.except(:long_name)
      @league.should_not be_valid
      @league.should have(2).error_on(:long_name)
      @league.errors[:long_name].should == ["can't be blank", 'is not included in the list']
      @league.long_name = 'National Football League'
      @league.should be_valid
    end
  end

end

是否有可能使用自定义匹配器或其他一些实用程序使这个更干燥?

【问题讨论】:

    标签: ruby-on-rails-3 refactoring rspec2 dry


    【解决方案1】:

    这是可能的,但我不建议这样做。这两个测试完全不同,以至于编写一个方法来包装它们会带来比看起来合理的更多的复杂性,并且如果这两个测试中的一个失败了,将使故障排除变得更加困难。

    【讨论】:

      【解决方案2】:

      你可能想看看shoulda

      这样你就可以写了

      describe League do
        subject {League.new}
      
        it {should validate_presence_of(:long_name)}
        it {should validate_presence_of(:short_name)}
      end
      

      还有许多其他匹配器用于验证和关联。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多