我在测试控制器时出现此错误
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: "example@mail.com", 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 :(得分:1)
根据您的要求,每个帖子必须与用户关联,因此您必须在帖子模型中进行belongs_to关联。类似的东西:
belongs_to :user
在用户模型中,例如:
has_many :posts
然后你的代码应该是:
setup do
user = User.create!(email: "example@mail.com",
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