I am running a Rails 4 application with rspec-rails 3.0.0 and musta-matchers 2.5.0, and I have an Event model that has some conditional checks:
class Event < ActiveRecord::Base
validates :name, :location, :time, :city, :zipcode, :user, :state, presence: true
validates :post_text, presence: true, if: :happened?
validates :pre_text, presence: true, unless: :happened?
belongs_to :community
belongs_to :user
belongs_to :state
def happened?
(self.time < Time.now) ? true : false
end
end
My event_spec.rb looks like this:
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
But when I run the tests, my block it { should validate_presence_of(:time) }fails because it continues to execute the remaining checks and throws an exception for conditional checks, because self.time is zero. I applied a hacker fix by checking time.present? in what happened? method. But can anyone help me figure out what is the best test method for conditional validations requiring a different field?
Tyler source
share