2015-06-25 32 views
-1

請幫忙寫模型的測試。如何爲鏈接模型編寫測試?

模型用戶:

class User < ActiveRecord::Base 
    has_many :guestbooks 
    has_secure_password 
end 

模型留言簿:

class Guestbook < ActiveRecord::Base 
    belongs_to :user 
end 

表用戶:

id: integer 
name: varchar 
email: varchar 
diary_name: varchar 

表留言簿:

id: integer 
message: text 
user_id: integer 

我試圖寫一個測試:

class GuestbookTest < ActiveSupport::TestCase 
    def setup 
    @user = User.create(
          name: 'namee', 
          email: '[email protected]', 
          diary_name: 'dnndndnррррnd', 
          password: 'qwerty', 
          password_confirmation: 'qwerty' 
         ) 
    end 

    test "should save guestbook for signin user" do 
    guestbook = Guestbook.new(message: 'dfsdfsf gdfgfdghfghfghf ghfgh ', user_id: @user) 
    assert guestbook.save 
    end 
end 

如收到以下錯誤消息的結果:

[email protected] ~/rails/ZSUM $ rake test:models 
Run options: --seed 19425 
# Running: 
F 
Finished in 0.349347s, 2.8625 runs/s, 2.8625 assertions/s. 
    1) Failure: 
GuestbookTest#test_should_save_guestbook_for_signin_user [/home/kalinin/rails/ZSUM/test/models/guestbook_test.rb:18]: 
Failed assertion, no message given. 
1 runs, 1 assertions, 1 failures, 0 errors, 0 skips 
+0

何去何從在「用戶」的其他列來自(密碼和password_confirmation)?你有'attr_accessible'用於'password'和'password_confirmation'嗎? – Makoto

+0

has_secure_password創建它們 – stackov8

回答

1

解決方案:

test "should save guestbook for signin user" do 
    guestbook = Guestbook.new(message: 'dfsdfsf gdfgfdghfghfghf ghfgh ', user_id: @user) 
    assert guestbook.save! 
    end 

,並在模型remakr名驗證:

class Guestbook < ActiveRecord::Base 
    # validates :name,  presence: true, length: { maximum: 200 } 
    validates :message, presence: true, length: { maximum: 1000, minimum: 10 } 

    belongs_to :user 
end