2013-06-05 159 views
0

我修整測試用戶是否具有創建後,「用戶」的默認角色默認的角色。對於角色,我有可以掃描並設計身份驗證。不能測試使用RSpec

在我的用戶模型我都這個剪斷

after_create :default_role 

private 
    def default_role 
     self.roles << Role.find_by_name("user") 
     self.save 
    end 

在user.spec.rb這個

it 'should have default role' do 
    role = Role.create! name: 'user' 
    user = User.create!(name: 'Andrew', email: "[email protected]", password: "12341234", password_confirmation: '12341234') 
    user.roles.count.should > 0 

和RSpec輸出

Failure/Error: user.roles.count.should > 0 
    expected: > 0 
     got: 0 

所以我通過合作調試nsole使用

user = User.create! name: 'Andrew', email: "[email protected]", password: "12341234", password_confirmation: '12341234' 

成功創建新的用戶實例後,我跑

user.has_role? :user 

,並返回真...

任何想法?

回答

1

在Rspec的創建用戶之後。您必須在創建它時立即重新加載「用戶對象」。重寫你的代碼像下面

it 'should have default role' do 
    role = Role.create! name: 'user' 
    user = User.create!(name: 'Andrew', email: "[email protected]", password: "12341234", password_confirmation: '12341234') 
    user.reload 
    user.roles.count.should > 0 
end 
+0

大.. !!!謝謝 :) –