【问题标题】:When validating ActiveRecord, I'm getting valid? => false but no errors in errors.count. How come?验证 ActiveRecord 时,我是否有效? => false 但errors.count 中没有错误。怎么会?
【发布时间】:2010-10-31 09:05:21
【问题描述】:

在 rspec 中创建 ActiveRecord 时,我使用固定装置来获取有效记录。 但是当在测试中使用 fxitures 时,它们似乎无法通过验证。 在以下示例中,员工似乎完全有效,但规范中的相关验证表明他们是无效的。

class Employee < ActiveRecord::Base
  validates_presence_of     :email
end

class User < ActiveRecord::Base
  validates_associated      :employee
end

#Command line debugger in 'debugger' (below) returns:
Employee.find(745185059).errors.count         # => 0
Employee.find(745185059).errors.full_messages # => []
Employee.find(745185059).valid?               # => true

例如:

describe SessionsController do
  fixtures :users, :employees

  describe "Logging in by cookie" do
    def set_remember_token token, time
      @user[:remember_token]            = token; 
      @user[:remember_token_expires_at] = time
      debugger
      @user.save! # THIS SAYS THE EMPLOYEE IS INVALID, but why, if the fixtures are good?
    end    
    it 'logs in with cookie' do
      stub!(:cookies).and_return({ :auth_token => 'hello!' })
      logged_in?.should be_true
    end
  end
end

任何想法为什么我得到验证失败? (当然,我剪掉了很多中间代码,有可能错误完全在其他地方)

【问题讨论】:

    标签: ruby activerecord rspec


    【解决方案1】:

    您可以在 .save 之后调试 @user(没有爆炸声!),这应该会添加错误,这可能是由模型回调或您的 validate 方法所做的事情引起的。在您的测试中,只需执行以下操作:

    @user.save
    puts @user.errors.inspect # or your command line debugger
    

    并在运行测试时读取输出。

    【讨论】:

    • 成功了!我不知道即使尝试 Employee(123).send(validate) 也行不通。非常感谢您的宝贵时间,奥马尔!
    猜你喜欢
    • 2012-04-27
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2022-01-19
    • 2022-07-19
    相关资源
    最近更新 更多