加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 验证ActiveRecord时,我有效吗? => false但在errors.

发布时间:2020-12-17 02:57:45 所属栏目:百科 来源:网络整理
导读:在rspec中创建ActiveRecord时,我使用fixture来获取有效记录. 但是当在测试中使用fxitures时,它们似乎无法通过验证. 在以下示例中,员工似乎完全有效,但规范中的关联验证表明它们无效. class Employee ActiveRecord::Base validates_presence_of :emailendclas
在rspec中创建ActiveRecord时,我使用fixture来获取有效记录.
但是当在测试中使用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

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

解决方法

您可以在.save(没有爆炸!)之后调试@user,它应该添加错误,它可能是由模型回调引起的,也可能是您的validate方法所做的事情.在你的测试中,只需:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读