2011-05-12 142 views
1

我可以在RSpec中找到測試設計用戶控制器和視圖的建議。我也看到了有關設計寶石代碼已經過測試的建議,因此花大量時間重新發明輪子是沒有用的。如何使用RSpec測試我的設計用戶模型驗證?

但是,我的用戶模型有其他字段,我需要在用戶註冊時進行驗證。我在user.rb模型中使用標準validates...語句。例如:

validates_presence_of  :nickname 

我想在我的user_spec.rb用簡單的驗證測試,但是當我嘗試創建這樣的用戶:

record = Factory.create(:user) 

我得到這個錯誤:

undefined method `encode!' for "Confirmation":String 

encode!方法不是來自我的代碼,它必須是設計正在使用的寶石之一,但我還沒有找到它。

我試着創建用戶使用User.new和工廠的女孩。無論哪種方式我都會得到同樣的錯誤這個規範正在傳遞,直到我更新了所有的寶石。不幸的是,我沒有記下當時更新的所有內容。我試着將設計回滾到以前的版本,但仍然得到相同的錯誤。

Rails 3,RSpec2

感謝您的任何建議。

回答

3

這似乎是罰款,可能是我的測試代碼,可以幫助你:

user_spec.rb

require 'spec_helper' 

describe User do 
    before :each do 
    @user = Factory.build(:user) 
    end 

    it "should not be valid without a first_name" do 
    @user.first_name = nil 
    @user.should_not be_valid 
    end 

end 

user.rb(型號)

class User < ActiveRecord::Base 

    validates_presence_of :first_name 

    # Include default devise modules. Others available are: 
    # :token_authenticatable, :confirmable, :lockable and :timeoutable 
    devise :database_authenticatable, :registerable, :lockable, 
     :recoverable, :rememberable, :trackable 
    # Setup accessible (or protected) attributes for your model 
    attr_accessible :login, :first_name, :email, :password, :password_confirmation, :remember_me 
    attr_accessor :login 

    devise :database_authenticatable, :recoverable, :validatable 

    protected 

    def password_required? 
    !persisted? || password.present? || password_confirmation.present? 
    end 



end 
+0

感謝。我認爲這可能是我創建用戶時包含(或缺失)的內容。你的工廠定義爲:用戶是什麼樣的?我的是: 'Factory.define:user,:class => User do | f | F.ID 327 f.email '[email protected]' f.password 'shadow33' f.password_confirmation 'shadow33' f.nickname '影子' end' – heyrolled 2011-05-12 12:12:42

+1

你舉的例子使我的罪魁禍首.. 。Factory.create(:user)'和'Factory.build(:user)'之間的區別。謝謝您的幫助! – heyrolled 2011-05-12 13:00:31