查看FactoryGirl对象时出现问题

时间:2011-09-16 17:12:20

标签: ruby-on-rails ruby ruby-on-rails-3 rspec factory-bot

我正在使用Ruby on Rails 3.0.10,RSpec 2和FactoryGirl。我有以下情况:

models/user_spec.rb文件中

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

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

factories/user.rb文件中

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

在我的user.rb文件中:

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

当我运行rspec命令时,我收到以下错误

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

究竟是什么问题,我该如何解决?


BTW :在models/user_spec.rb文件中,我可以使用以下内容

let(:user) { User.create }

它会起作用,但我更喜欢使用FactoryGirl gem 您对此有何建议?

1 个答案:

答案 0 :(得分:0)

您可以尝试按以下方式修改规范并查看结果:

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