views:

274

answers:

4

Hi,

I am writing my specs on my model Thing which has a date field which should be after the date of creation, thus I use the *validate_timeliness* plugin like that

validate_date :date, :after Time.now

I want to be able to add some Things with an anterior date but validation fails. I want to bypass the validation when creating some Things with the machinist factory.

Any clue ?

A: 

If you call your_obj.save with a Boolean parameter =true like this: some_obj.save!(true), than all validations would be skipped. This is probably the undocumented ActiveRecord feature that is widely used in my company :)

Alex Kaushovik
A: 

Hmm, there's no straightforward way to do with Machinist itself. But you can try to trick it ... in spec/spec_helper, redefine the Thing model before the Machinist blueprints are loaded.

class Thing

def before_validation
  self.date = 1.hour.from_now
end

end
Ahsan Ali
A: 

Shouldn't your validation ensure that the date is after the created_at attribute?? Rather than Time.now???

You shouldn't be trying to use invalid data in your tests, what you probably should do instead is fudge the created at time.

@thing = Thing.make(:created_at => 1.day.ago)

The only reason to try and put a time in the past in your spec surely should be to test that the validation is indeed working ..

@thing = Thing.make_unsaved(:date => 1.day.ago)
@thing.should have(1).error_on(:date)

Is there a reason why you want to do this? What are you trying to test??

railsninja
I wanted to simulate a data which was added a day ago.Yesterday this could be added, today not.I found a trick to do that by setting the Time.now to yesterday. I will try to use the time_travel plugin, but this makes sense.I will also test with created_at rather than Time.now
toofancy
A: 

You can catch the exception thrown by the validation. If you require the following code in your spec_helper after requiring machinist. To use it you can add a false as the first argument to #make.

module Machinist
  module ActiveRecordExtensions
    module ClassMethods
      def make_with_skip_validation(*args, &block)
        validate = !(!args.pop if ( (args.first == true) || (args.first == false) ))
        begin
          make_without_skip_validation(*args, &block)
        rescue ActiveRecord::RecordInvalid => invalid
          if validate
            raise invalid
          else
            invalid.record.save(false)
          end
        end  
      end

      alias_method_chain :make, :skip_validation
    end
  end
end
Kamal