uozsew
Last Updated: February 25, 2016
·
782
· abe33
6c20dd9e98b93e3b3b36cf92b3cfcc39

Validates field uniqueness with state_machine and factory_girl

Include this helper in RSpec::Core::ExampleGroup :

module StateMachineHelper
  module ExampleGroupMethods

    def it_should_validate_uniqueness_of field
      @field = field
      self
    end

    def with_factory factory
      @factory = factory
      self
    end

    def when_state_is state
      factory = @factory
      field = @field

      it "#{@factory} should validate uniqueness of #{@field} when state is #{@state}" do
        instance1 = create factory, state
        instance2 = create factory, state
        instance2.send("#{field}=", instance1.send(field))
        instance2.save

        instance2.errors[field].should( include('has already been taken'),
          "Expected errors to include 'has already been taken' when #{field} is set to '#{instance1.send field}', got errors: #{instance2.errors[field]}"
        )
      end
    end
  end
end

And then you can write:

it_should_validate_uniqueness_of(:field)
  .with_factory(:factory)
  .when_state_is(:trait)
Say Thanks
Respond