2015-10-01 76 views
0

我有這樣的錯誤,當我'測試我控制器Rails的未定義的方法 'FULL_NAME'

ActionView::Template::Error: undefined method `full_name' for nil:NilClass 

我的測試:

class PostsControllerTest < ActionController::TestCase 
include Devise::TestHelpers 

setup do 
    @post = Post.create!(title: "my title", content: "bla bla bla") 
    user = User.create!(email: "[email protected]", first_name: "name", last_name: "surename", 
        password: "password", password_confirmation: "password") 
    sign_in user 
end 

test "should show post" do 
    get :show, id: @post 
    assert_response :success 
end 

FULL_NAME方法模型:

def full_name 
    "#{first_name} #{last_name}" 
end 

和我的看法:

Wrote by 
    = @post.user.full_name 

感謝您的幫助

+0

嘿認爲thier是你的職位多數民衆贊成在沒有用戶爲什麼它返回這個例外 –

回答

1

根據您的要求,每個帖子必須與用戶關聯,因此您必須在發佈模型中使用belongs_to關聯。是這樣的:

belongs_to :user 

,並在用戶模型,如:

has_many :posts 

那麼你的代碼應該想:

setup do 
    user = User.create!(email: "[email protected]", 
     first_name: "name", last_name: "surename", 
     password: "password", password_confirmation: "password") 
    @post = user.posts.create!(title: "my title", content: "bla bla bla") 
    sign_in user 
end 
+0

我有協會,但我改變了你的設置代碼,它的工作原理。謝謝! – exerq

相關問題