开发者

Trouble on rspecting a FactoryGirl object

开发者 https://www.devze.com 2023-04-05 15:23 出处:网络
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

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      =&开发者_如何学Pythongt; 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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消