1

I am using Ruby on Rails 3.0.10, RSpec 2 and FactoryGirl. I have the following scenario:

In the models/user_spec.rb file I have

describe User do
  let(:user) { Factory(:user) }

  it "should have a 'registered' authorization do
    user.authorization.should == "registered"
  end
end

In the factories/user.rb file I have

FactoryGirl.define do
  factory :user, :class => User do |user|
    user.authorization 'registered'
  end
end

In the user.rb file I have:

class User < ActiveRecord::Base
  DEFAULT_AUTHORIZATION = 'registered'

  validates :authorization,
    :inclusion => {
      :in      => Authorization.all.map(&:name),
      :message => "authorization is not allowed"
    },
    :presence  => true

  before_validation :fill_user_create, :on => :create


  private

  def fill_user_create
    self.authorization = Authorization::DEFAULT_AUTHORIZATION
  end
end

When I run the rspec command I get the following error:

User should have a default 'registered' Authorization
Failure/Error: let(:user) { Factory(:user) }
ActiveRecord::RecordInvalid:
  Validation failed: Users authorization is not allowed

What is exactly the problem and how can I solve that?


BTW: In the models/user_spec.rb file I can use something like the following

let(:user) { User.create }

and it will work, but I prefer to use the FactoryGirl gem. What do you advice about?

Backo
  • 18,291
  • 27
  • 103
  • 170

1 Answers1

0

Could you try modifying your spec as below and check what the results are:

it "should have a 'registered' authorization" do
  system_names = Authorization.all.map(&:system_name)
  system_names.should have_at_least(1).item
  system_names.should include('registered')
  user.authorization.should == "registered"
end
jake
  • 2,371
  • 1
  • 20
  • 31
  • See http://stackoverflow.com/questions/7457403/trouble-on-evaluating-other-model-data for more information. – Backo Sep 17 '11 at 20:00