如何使用rspec-rails 3.0.0和shoulda-matcher 2.5.0测试条件验证
发布时间:2020-12-17 03:06:40 所属栏目:百科 来源:网络整理
导读:我正在使用rspec-rails 3.0.0运行Rails 4应用程序并且应该匹配2.5.0,并且我有一个具有一些条件验证的事件模型,如下所示: class Event ActiveRecord::Base validates :name,:location,:time,:city,:zipcode,:user,:state,presence: true validates :post_tex
我正在使用rspec-rails 3.0.0运行Rails 4应用程序并且应该匹配2.5.0,并且我有一个具有一些条件验证的事件模型,如下所示:
class Event < ActiveRecord::Base validates :name,:location,:time,:city,:zipcode,:user,:state,presence: true validates :post_text,presence: true,if: :happened? validates :pre_text,unless: :happened? belongs_to :community belongs_to :user belongs_to :state def happened? (self.time < Time.now) ? true : false end end 我的event_spec.rb看起来像: require 'spec_helper' describe Event do before { @event = FactoryGirl.build(:future_event) } subject { @event } it { should validate_presence_of(:time) } it { should validate_presence_of(:name) } it { should validate_presence_of(:location) } it { should validate_presence_of(:user) } it { should validate_presence_of(:city) } it { should validate_presence_of(:state) } it { should validate_presence_of(:zipcode) } it { should belong_to(:state) } it { should belong_to(:user) } it 'has pre_text if future event' do expect(FactoryGirl.create(:future_event)).to be_valid end it 'has post_text if past event' do expect(FactoryGirl.create(:past_event)).to be_valid end end 但是当我运行测试时,我的{should validate_presence_of(:time)}块失败,因为它继续运行剩余的验证并在条件验证上抛出异常,因为self.time为nil.我通过检查time.present实现了一个hacky修复程序?在发生了什么?方法.但是,任何人都可以帮助我理解测试需要存在另一个字段的条件验证的最佳方法是什么? 解决方法
是的,不幸的是没有其他办法.事实上,在保存事件记录之前,技术上允许时间为零,所以如果您碰巧打电话给#happened?在时间设置之前,它将引发异常.因此,如果我编写这段代码,我会亲自检查#happened?,因为这是一个你需要处理的情况(不管这实际发生的可能性).
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |