Last Updated: February 25, 2016
·
939
· abe33

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)