Search code examples
ruby-on-railsruby-on-rails-3rspecfactory-botrspec-rails

Factory-girl create that bypasses my model validation


I am using Factory Girl to create two instances in my model/unit test for a Group. I am testing the model to check that a call to .current returns only the 'current' groups according to the expiry attribute as per below...

  describe ".current" do
    let!(:current_group) { FactoryGirl.create(:group, :expiry => Time.now + 1.week) }
    let!(:expired_group) { FactoryGirl.create(:group, :expiry => Time.now - 3.days) }

    specify { Group.current.should == [current_group] }
  end

My problem is that I've got validation in the model that checks a new group's expiry is after today's date. This raises the validation failure below.

  1) Group.current 
     Failure/Error: let!(:expired_group) { FactoryGirl.create(:group, :expiry => Time.now - 3.days) }
     ActiveRecord::RecordInvalid:
       Validation failed: Expiry is before todays date

Is there a way to forcefully create the Group or get around the validation when creating using Factory Girl?


Solution

  • This isn't very specific to FactoryGirl, but you can always bypass validations when saving models via save(validate: false):

    describe ".current" do
      let!(:current_group) { FactoryGirl.create(:group) }
    
      let!(:old_group) do
        g = FactoryGirl.build(:group, expiry: Time.now - 3.days)
        g.save(validate: false)
        g
     end
          
     specify { Group.current.should == [current_group] }
    end