2009-06-04 13 views
3

當在rspec中創建一個ActiveRecord時,我使用燈具來記錄有效的記錄。 但是當在測試中使用fxitures時,它們似乎未通過驗證。 在以下示例中,員工似乎完全有效,但規範中的相關驗證表明他們無效。驗證ActiveRecord時,我變得有效了嗎? => false,但在errors.count中沒有錯誤。怎麼來的?

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 

任何想法,爲什麼我得到驗證失敗? (當然,我刪掉了很多中間代碼,有可能這個錯誤在其他地方完全是這樣)

回答

5

你可以在.save之後調試@user(沒有bang!),應該添加錯誤,它可能是由模型回調引起的,也可能是你的驗證方法所做的事情。在你的測試中,只需要:

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

並在運行測試時讀取輸出。

+0

這個伎倆! 我不知道,即使嘗試 員工(123).send(驗證) 將無法​​正常工作。感謝你的時間,奧馬爾! – btelles 2009-06-05 04:20:25

相關問題