2014-01-25 95 views
0

當我運行RSpec時出現錯誤can't dup NilClasscan not dup NilClass - Rails

我已經嘗試添加unloadable但它不能解決它。

我想這是導致錯誤的函數:

class User < ActiveRecord::Base 

    before_save :create_permalink 

    validates :username, presence: true, length: { maximum: 50, minimum: 3 }, 
         uniqueness: { case_sensitive: false } 
    validates :permalink, presence: true, length: { maximum: 50, minimum: 3 }, 
         uniqueness: { case_sensitive: false } 
    private 

    def create_permalink 
     self.permalink = username.dup.parameterize 
    end 
end 

user_spec.rb

require 'spec_helper' 

describe User do 
    before do 
    @user = User.new(name: Faker::Name.name, username: "example", 
        email: Faker::Internet.email, password: "password", 
        password_confirmation: "password") 
    end 

    . 
    . 
    . 

end 

失敗的測試包括:

it { should validate_presence_of(:username) } 
it { should validate_uniqueness_of(:permalink) } 

我也嘗試添加:

config.reload_plugins = true if RAILS_ENV == ‘development’ 

我的environment.rb文件,但再次沒有工作。

我會如何阻止這種情況發生,因爲它會讓我的測試失敗?

+0

那麼你的問題是什麼? –

+0

@PeterAlfvin道歉,我雖然很明顯。現在的問題在底部。 – Tim

回答

0

您有一個測試,創建一個User對象與零username。有幾種可能的解決方法,它很難在沒有看到測試代碼的情況下選擇一個。它可以像設置測試用戶時指定用戶名一樣簡單,例如,

user = User.create username: 'Test User' 

包含在問題,如果它比這更復雜的RSpec的測試代碼。

因爲它代表的用戶名是您的用戶模型所需的字段,因此它可能是值得加入驗證它:

class User < ActiveRecord::Base 
    validates :username, presence: true 
    ... 
end 

驗證的before_save過濾器之前運行,所以你會在你的測試中獲得更有意義的錯誤。

+0

我已經用我的用戶驗證更新了這個問題,當我運行測試和運行RSpec時,驗證已經存在。 – Tim

+0

您是否也可以包含失敗的代碼示例('it' block)?在'before'塊中設置的'@ user'很好(它設置了'username'字段),所以在失敗的測試中可能會出現一個不同的'User'對象。 – Steve

+0

我相信我發現了這個問題,我正在使用shoulda gem進行測試,看起來存在兼容性問題。 – Tim