Search code examples
ruby-on-railsvalidationrspecrspec-rails

RSpec skip one of many validations in creating an object


I am trying to write RSpec test for one of my Models. I want my test to test validations as well, but I will like to skip a specific validation, only in the test.

I understand that to skip validations, I can do pass in a (:validate => false) option to my create or save action, but my understanding is that this will skip all the validations for the Model.

What I want is to skip only a specific validation.

The validations in my model is as follow:

  validates :user_id, :name, :description, :address, :image, :spot_type, :internet_options, presence: true
  validate :image_size_validation

I want all validations to take effect, but only skip validation for presence of image. Reason is that I don't want to be populating the s3 space where I'm hosting images, each time I run the test.


Solution

  • If you want to specifically test validations, you may just build objects without saving them and then test calling #valid? method. Something like (assuming FactoryGirl for creation)

    expect(build(:something, { field: value })).to be_valid
    

    If you want to save objects with validations running, but avoid using S3, as suggested by @apneadiving in the comment, you may change storage setting for test environment. You can do that by modifying the carrierwave initializer like

    CarrierWave.configure do |config|
      if Rails.env.test?
        config.storage = :file
      end
    end