Rails validation test not passing -


in our rails app, have following models:

class user < activerecord::base   has_many :administrations, dependent: :destroy   has_many :calendars, through: :administrations end  class administration < activerecord::base   belongs_to :user   belongs_to :calendar end  class calendar < activerecord::base   has_many :administrations, dependent: :destroy   has_many :users, through: :administrations end 

we tried validate administration model following administration_test.rb test file:

require 'test_helper'

class administrationtest < activesupport::testcase   def setup     @user = users(:noemie)     @administration = administration.new(user_id: @user.id, calendar_id: @calendar_id)   end    test "should valid"     assert @administration.valid?   end    test "user id should present"     @administration.user_id = nil     assert_not @administration.valid?   end    test "calendar id should present"     @administration.calendar_id = nil     assert_not @administration.valid?   end  end 

when run test, following results:

fail["test_calendar_id_should_be_present", administrationtest, 2015-06-30 07:24:58 -0700]  test_calendar_id_should_be_present#administrationtest (1435674298.26s)         expected true nil or false         test/models/administration_test.rb:21:in `block in <class:administrationtest>'   fail["test_user_id_should_be_present", administrationtest, 2015-06-30 07:24:58 -0700]  test_user_id_should_be_present#administrationtest (1435674298.27s)         expected true nil or false         test/models/administration_test.rb:16:in `block in <class:administrationtest>' 

we kind of lost: right way right test?

if no, how should write it? if yes, how can make pass?

the problem not test rather expecting wrong outcome.

belongs_toin activerecord not add validation, macro creates relation.

to validate relation use validates_associated calls #valid? on each of associated records , validates_presence_of ensure associated record present.

class administration < activerecord::base   belongs_to :user   belongs_to :calendar   validates_associated :user    validates :user, presence: true end 

when testing validations better write on assertions on errors hash, assert_not @administration.valid? give false positive if validation fails other reason.

bad:

test "user id should present"   @administration.user_id = nil   assert_not @administration.valid? end 

good:

test "user id should present"   @administration.user_id = nil   @administration.valid?   assert @administration.errors.key?(:user) end 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -