Keep DRY but want to repeat for various reasons

So, in my evolving rspecs for my RoR model, I ended up with two tests in exactly the same way:

it 'is valid when x is zero' do
    foo = build(:foo, x: 0, y: 10)
    expect(foo.valid?).to be_truthy
end
it 'is valid when y is ten' do
    foo = build(:foo, x: 0, y: 10)
    expect(foo.valid?).to be_truthy
end

This happened because I wrote a specification to check x first, and then added spec for y after.

Obviously, time for refactoring. I could remove one of the specs because they are duplicates: keep it DRY.

Now the insides of each spec may be exactly the same, but the descriptions itare different. I do not want to lose the information contained there.

My questions are: is it acceptable in this case to preserve the unique specifications of duplicates, or should I "combine" them and change the description it? Maybe:

it 'is valid when x is zero and y is ten' do
    foo = build(:foo, x: 0, y: 10)
    expect(foo.valid?).to be_truthy
end

, , , ( Foo). . .

, ?

+4
3

DRY , , .

it 'is valid when x is zero' do
  foo = build(:foo, x: 0)
  expect(foo.valid?).to be_truthy
end

! , .

:

  • . .new .
  • , .
  • , .
  • - .

RSpec.describe Foo do
  describe "validations" do
    describe 'x' do
      it "validates that x is a number between 1 and 10" do
        expect(Foo.new(500).valid?.errors[:x]).to include "must be less than or equal to 10".
        expect(Foo.new(10).valid?.errors).to_not have_key :x
      end
    end

    describe 'y' do
      it "validates that y is a number that is less than 15" do
        expect(Foo.new(500).valid?.errors[:y]).to include "must be less than 15".
        expect(Foo.new(10).valid?.errors).to_not have_key :y
      end
    end
  end
end
+2

, , , DRY.

, -, .

foo , x , y .

it 'is valid when x is zero' do
  foo = build(:foo, x: 0)
  expect(foo.valid?).to be_truthy
end

foo , y , x .

it 'is valid when y is ten' do
  foo = build(:foo, y: 10)
  expect(foo.valid?).to be_truthy
end

, .

:

it 'allows x to equal zero' do
  foo = build(:foo, x: 0)
  foo.valid?
  expect(foo.errors).to_not have_key(:x)
end

it 'allows y to be ten' do
  foo = build(:foo, y: 10)
  foo.valid?
  expect(foo.errors).to_not have_key(:y)
end
+2

, , .

, , , . DRY , , . - ( ) , , , , . , , - - ( " ", : " ?" " ?". , , , , - , , , , , , .

+1
source

Source: https://habr.com/ru/post/1657791/


All Articles