Factory-girl create that bypasses my model validation

后端 未结 9 2154
既然无缘
既然无缘 2021-01-30 06:31

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 ac

相关标签:
9条回答
  • 2021-01-30 06:54

    For this specific date-baesd validation case, you could also use the timecop gem to temporarily alter time to simulate the old record being created in the past.

    0 讨论(0)
  • 2021-01-30 06:54

    It is not best to skip all validation of that model.

    create spec/factories/traits.rb file.

    FactoryBot.define do
      trait :skip_validate do
        to_create { |instance| instance.save(validate: false) }
      end
    end
    

    fix spec

    describe ".current" do
      let!(:current_group) { FactoryGirl.create(:group, :skip_validate, :expiry => Time.now + 1.week) }
      let!(:expired_group) { FactoryGirl.create(:group, :skip_validate, :expiry => Time.now - 3.days) }
    
      specify { Group.current.should == [current_group] }
    end
    
    0 讨论(0)
  • 2021-01-30 06:56

    I prefer this solution from https://github.com/thoughtbot/factory_girl/issues/578.

    Inside the factory:

    to_create {|instance| instance.save(validate: false) }
    

    EDIT:

    As mentioned in the referenced thread, and by other's comments/solutions, you'll likely want to wrap this in a trait block to avoid confusion/issues elsewhere in your tests; for example, when you're testing your validations.

    0 讨论(0)
提交回复
热议问题