Rails: Test :: Unit Why do I need to claim that something is valid or invalid before any other statements

This seems a little odd when running unit test to check if my header length is> 10, my test will pass if I turn on "assert product.invalid?". before any other approves it as follows:

require 'test_helper' class ProductTest < ActiveSupport::TestCase test "product title is too short" do product = Product.new(:title => "My lady", :description => "yyy", :price => 1 ) assert product.invalid? assert_equal "must be atleast 10 characters long.", product.errors[:title].join('; ') end end 

However, if I do not include "assert product.invalid?" before assert_equal I get this error 1) Failure: test_product_title_is_too_short blah blah blah ("must have at least 10 characters"), but there was ("").

How does Test :: Unit work? Should I argue that something is valid or invalid before embarking on other tests? What kind of test initialization?

+4
source share
2 answers

Actually, this is not a characteristic of the test environment, but rather ActiveRecord.

When creating an object using ActiveRecord, you can assign checks to ensure certain things about the attributes of objects (as you have on your object). However, these checks only start at a specific time, and as you can see, the β€œnew” method is not one of these times. However, asking about the validity of an object with an invalid? method, you thereby invoked checks.

I think it is more natural to use the "create" method instead of the "new" method to run validation for your object. automatically create validation checks that eliminate your call to "invalid?" in your test and should still fill out the error hash code as desired:

 product = Product.create(:title => "My lady", :description => "yyy", :price => 1 ) assert_equal "must be atleast 10 characters long.", product.errors[:title].join('; ') 

Similar to the 'create' method, create is created! a method that will actually throw an exception if any validation fails. create will simply return false and populate the error hash code.

For more information about checks, check out: http://guides.rubyonrails.org/active_record_validations_callbacks.html

+3
source

This has nothing to do with Test :: Unit. This is the function of the rails. Checks are only performed when .valid? called .valid? or one of the .save versions. You can learn more about the callback chain here: http://guides.rubyonrails.org/active_record_validations_callbacks.html#when-does-validation-happen

+3
source

All Articles