thoughtbot/shoulda-matchers — Issue #58: validate_uniqueness_of breaks with factory girl
Author: fourcolors
Created: 2012-02-26 04:38:12+00:00
State: open

Hi I have an Invitation model that I'm testing which currently just has an email and token. My test looks kind of like this.

### Model

```ruby
class Invitation < ActiveRecord::Base
#Validations
validates :email, :presence => true
validates :token, :uniqueness => true

#callback
before_validation :generate_token

private

def generate_token
self.token = Digest::SHA1.hexdigest([Time.now, rand].join)
end
end
```

### Spec

```ruby

require 'spec_helper'

describe Invitation do
describe "Validations" do
it{ should validate_presence_of(:email)}
it{ FactoryGirl.create(:invitation); should validate_uniqueness_of(:token)}
end
end
```

### Error message

```bash
.F

Failures:

1) Invitation Validations
Failure/Error: it{ FactoryGirl.create(:invitation); should validate_uniqueness_of(:token)}
Expected errors to include "has already been taken" when token is set to nil, got errors: ["email can't be blank (nil)"]
# ./spec/models/invitation_spec.rb:6:in `block (3 levels) in '

Finished in 0.12196 seconds
2 examples, 1 failure

Failed examples:

rspec ./spec/models/invitation_spec.rb:6 # Invitation Validations
```

### Factory Girl defined

```ruby
FactoryGirl.define do
factory :invitation do
sequence(:email){|n| "email#{n}@domain.com" }
token "5m234m3m23mf3"
end
end
```

As you can see, for some reason when the "uniqueness_of" matcher is called, it's trying to create an invitation without an email address. I can confirm everything works as I would like in my rails console however things are breaking in my test. I'm pretty sure this is something to do with the matchers however this could be something with factory girl but I'm still unsure.

Unless I'm missing something obvious here, am I right to presume something is broken?