Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds assert_error and assert_no_error #51774

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

DanielaVelasquez
Copy link

@DanielaVelasquez DanielaVelasquez commented May 9, 2024

Motivation / Background

Ensuring the correctness of validations in Rails models is a fundamental aspect of robust testing. However, the current approach to such validations can often lead to cluttered and less readable test code. For instance, manually asserting validation errors requires multiple lines of code, detracting from the clarity of the test suite. This PR addresses this issue by introducing a streamlined solution that enhances readability and conciseness in model testing.

test "name cannot be blank" do
    user = users(:one)
    
   user.validate
   refute_empty user.errors.where(:name, :blank)
end

or

test "name cannot be blank" do
    user = users(:one)
    
   user.validate
   assert user.errors.added? :name, :blank
end

Detail

This PR introduces a new assertion method, assert_error and assert_invalid, designed to simplify the validation testing process. With them developers can now verify the presence of specific validation errors with a single, expressive line of code. This enhancement not only improves the readability of tests but also promotes better understanding and maintenance of the validation logic within Rails models.

test "name cannot be blank" do
    user = users(:one)
    
   assert_not_valid :name, :blank, user
end
test "name cannot be blank" do
    user = users(:one)
    user.validate
    
   assert_error :name, :blank, user
end

In the same way the validation assert_valid and assert_no_error ensures that the model has no errors for a specific field

test "name is not blank" do
    user = users(:one)
    
   assert_no_error :name, :blank, user
end
test "name is not blank" do
    user = users(:one)
    
   assert_valid :name, :blank, user
end

Checklist

Before submitting the PR make sure the following are checked:

  • This Pull Request is related to one change. Unrelated changes should be opened in separate PRs.
  • Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
  • Tests are added or updated if you fix a bug or add a feature.
  • CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.

# Assertion that an active model has a specific invalid field
#
# assert_invalid :name, :blank, :user
def assert_invalid(attribute, type, obj, msg = nil)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking about this, having only assert_invalid feels like it doesn't match the framework's other assertions. I think the framework should support assert_valid and assert_not_valid. What do you think about changing this PR to support those?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a great idea, thank you for the feedback. I updated it and changed the name of the method to make it more descriptive so it's clear that it references errors in the model.

@DanielaVelasquez DanielaVelasquez changed the title Adds assert_invalid Adds assert_error and assert_no_error May 11, 2024
@rafaelfranca
Copy link
Member

Does this work when the error is added as a string instead of symbol? errors.add(:name, "Some error")

Comment on lines 264 to 286
# Assertion that an active model doesn't have an error on a field
#
# assert_no_error :name, :blank, :user
def assert_no_error(attribute, type, obj, msg = nil)
raise ArgumentError.new("#{obj.inspect} does not respond to #validate") unless obj.respond_to?(:validate)

obj.validate
msg = message(msg) {
data = [attribute, type]
"Expected %s to not be %s" % data
}
assert_empty obj.errors.where(attribute, type), msg
end

# Assertion that an active model has a specific error on a field
#
# assert_error :name, :blank, :user
def assert_error(attribute, type, obj, msg = nil)
raise ArgumentError.new("#{obj.inspect} does not respond to #validate") unless obj.respond_to?(:validate)

obj.validate
msg = message(msg) {
data = [attribute, type]
"Expected %s to be %s" % data
}
refute_empty obj.errors.where(attribute, type), msg
end
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To share some prior art in this space, thoughtbot/shoulda-matchers might be of interest. It is a 14 year old project that provides Active Model validation assertions (amongst other things).

Like this proposal, it also invokes #validate on the object directly. Unlike this proposal, it names its matches in a way that communicates that it's invoking #validate (for example, validates_presence_of, validates_uniqueness_of, etc.).

Callers of an assert_no_error assertions might be surprised to learn that it's also invoking #validate, since #validate clears any errors present on the object before re-validating. Depending on the details of the test itself, that kind of reseting might un-do and remove errors added during that test.

As a caller, I might expect assert_no_error to only make assertions about the errors available by the subject under test's #errors method.

If this proposal is deemed viable, what do you think about introducing both assert_valid and assert_not_valid assertions that invoke assert_no_error and assert_error (respectively)? That way, callers can benefit from the convenience of assert_valid or assert_not_valid while also being able to drop down to the finer-grained assert_error or assert_no_error.

I'm imagining something like:

      # Assertion that an active model doesn't have an error on a field
      #
      #   assert_no_error :name, :blank, :user
      def assert_no_error(attribute, type, obj, msg = nil)
        msg = message(msg) {
          data = [attribute, type]
          "Expected %s to not be %s" % data
        }
        assert_empty obj.errors.where(attribute, type), msg
      end
      
      # Assertion that an active model has a specific error on a field
      #
      #   assert_error :name, :blank, :user
      def assert_error(attribute, type, obj, msg = nil)
        msg = message(msg) {
          data = [attribute, type]
          "Expected %s to be %s" % data
        }
        refute_empty obj.errors.where(attribute, type), msg
      end
      
      def assert_not_valid(attribute, type, obj, msg = nil)
        raise ArgumentError.new("#{obj.inspect} does not respond to #validate") unless obj.respond_to?(:validate)

        obj.validate
        assert_error(attribute, type, object, msg)
      end

      def assert_valid(attribute, type, object, msg = nil)
        raise ArgumentError.new("#{obj.inspect} does not respond to #validate") unless obj.respond_to?(:validate)

        obj.validate
        assert_empty obj.errors, msg
      end

It's worth mentioning that assert_valid doesn't exactly mean "there are no errors under this particular key", it means "there are no errors.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are there plans to support Active Model Validation Contexts?

When invoking the version of assert_no_error that does not call #validate, it's up to the test code that precedes the assertion to validate with the proper context.

When invoking the assert_valid and assert_not_valid variations, there isn't a way to forward along any contextual information (like an :on option). This is also true of the currently proposed assert_error and assert_no_error definitions that call #validate directly.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Callers of an assert_no_error assertions might be surprised to learn that it's also invoking #validate
Agreed, thanks for the feedback. I will go ahead and make those changes.

Regarding

Are there plans to support Active Model Validation Contexts?

This can be another type of assertion. However, the current change aims to focus on a model that went through the process of doing its validations.

PS: This is my first contribution ever to Rails and if it's better to ship a more defined feature then I am onboard with adding more stuff. LMK what's the approach generally taken. I am thinking this in terms of small deliverable.

@DanielaVelasquez DanielaVelasquez force-pushed the assert-invalid branch 2 times, most recently from 192aebd to c7d35c1 Compare May 15, 2024 00:51
@rails-bot rails-bot bot added the railties label May 15, 2024
@DanielaVelasquez DanielaVelasquez force-pushed the assert-invalid branch 3 times, most recently from 05603dc to 0568062 Compare May 15, 2024 01:10
Allows asserting that the correct validations were added to a model.
Streamline the testing process for validations and make it easier for developers to understand the purpose of each test case.
@DanielaVelasquez
Copy link
Author

Does this work when the error is added as a string instead of symbol? errors.add(:name, "Some error")

It does, since it's using added to make the assertions

@eileencodes
Copy link
Member

I'm fine being veto'd by someone else on Core but I don't like assert_error and assert_no_error because I think it's too close to assert_raises and assert_nothing_raised.

assert_validation_error and assert_no_validation_error is maybe better? Kind of a mouthful though 🤔

@zzak
Copy link
Member

zzak commented May 18, 2024

If the name is generic enough like this, and it really only applies to ActiveModel objects, then it should only be available in something like ActiveModel::TestCase 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants