t6d / smart_properties

Ruby accessors on steroids
MIT License
177 stars 20 forks source link

Required behavior differs when the required key is missing vs when it is nil #98

Open marcin-drozd opened 1 year ago

marcin-drozd commented 1 year ago

I think this may be a more layered issue so I will try to provide examples. The behavior of the required attribute differs depending on whether the property is nil or just missing.

One aspect of the issue is that I think the tests do not cover the case of happy path when conditionally required property should be allowed based on the condition.

This is the test that I believe would cover this:

it "should not raise an error when created without a name and anonymous being set to true" do
  expect { klass.new name: nil, anonymous: true }.to_not raise_error
end

it would fail currently for the current setup:

subject(:klass) do
  DummyClass.new do
    property :name, required: lambda { not anonymous }
    property :anonymous, accepts: [true, false], default: true
  end
end

but it would be successful for this setup:

subject(:klass) do
  DummyClass.new do
    property :anonymous, accepts: [true, false], default: true
    property :name, required: lambda { not anonymous }
  end
end

In the first case the anonymous would be nil vs in the second one it would be true. So the order of properties is important.

However, there is another layer to all of this, because this test:

it "should not raise an error when created with no arguments" do
  expect { klass.new }.to_not raise_error
end

passes successfully, but I think it is just because the required attribute is not checked in that case for the missing key (?). It is only tested for the property it depends on - anonymous in that case which does not have any requirement. This situation does not happen if required is just a boolean.