Ruby on Rails: Should all my ActiveRecord callback methods be private?

I have an ActiveRecord model that has some callbacks and user checks that I want to test. This means that I have to make them publicly available. Is this a good practice or is there a better solution in this case?

Examples of methods I want to test:

def before_validation original.edit(self) if original end validate :unique?, on: :create def unique? return true if original.blank? errors.add(:base, 'The entry already exists') false end 

In other words:

  • If I want to test the before_validation method, should I make it public and call test_object.before_validation directly in my Rspec model file?
  • If I want to test not only this unique verification method (?) That is called during verification, but also the method itself, do I need to make it also unique? ()?

The problem is that none of these methods that I use outside my model (therefore they should be private), but how can I test without making them public?

+6
source share
1 answer

It's easy to get into a test implementation, but it's a good candidate for testing behavior.

Ask yourself what you do before you actually do the check. Then do yourself a test, which, given certain inputs, you will get certain outputs, if and only if yours before the test works.

As a simple example, suppose you have a user model with a simple name attribute, and you have before_validation that just does:

 name = "Auto-generated name." if name.blank? 

Then you can write a test for it as follows:

 it "gets an auto-generated name if none is specified." do user = User.create! user.name.should eq "Auto-generated name." end it "does not get an auto-generated name if one is specified." do user = User.create!(:name => "Test Name") user.name.should eq "Test Name" end 

So, as you can see, this test checks the validation, but it does not need to be publicly available, because you are just checking its behavior. Does the same apply to the unique? method unique? . Give it specific inputs and test the behavior without worrying about which particular method was used or any other implementation details.

+3
source

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


All Articles