我是Rails的新手,並且一直關注在線教程,其中涉及創建一個簡單的博客站點。我正在爲控制器和模型添加測試項目。當我嘗試運行posts_controller_test.rb,我得到以下錯誤:錯誤:未定義的方法名稱爲零:NilClass
Error:
PostsControllerTest#test_should_get_index:
ActionView::Template::Error: undefined method `name' for nil:NilClass
app/views/posts/index.html.erb:7:in `block in _app_views_posts_index_html_erb__805998677_54338856'
app/views/posts/index.html.erb:1:in `_app_views_posts_index_html_erb__805998677_54338856'
test/controllers/posts_controller_test.rb:5:in `block in <class:PostsControllerTest>'
bin/rails test test/controllers/posts_controller_test.rb:4
這裏是我的posts_controller_test.rb:
class PostsControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get posts_url
assert_response :success
assert_not_nil assigns(:posts)
end
end
的教程是在早期版本的軌道,其用於生產get:index,我在rails 5中不贊成使用它,建議使用URL而不是動作名稱。
有趣的是,如果我執行控制器home_controller_test.rb,我還沒有修改,我得到如下不同的錯誤:
Error:
HomeControllerTest#test_should_get_index:
NameError: undefined local variable or method `home_index_url' for #<HomeControllerTest:0x67df790>
test/controllers/home_controller_test.rb:5:in `block in <class:HomeControllerTest>'
bin/rails test test/controllers/home_controller_test.rb:4
這裏是home_controller_test.rb:
require 'test_helper'
class HomeControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get home_index_url
assert_response :success
end
end
任何有關這些問題可能的幫助將不勝感激。
添加我的帖子索引視圖:
<% @posts.each do |post| %>
<div class="post">
<h2 class="title"><%= link_to post[:title],post %></h2>
<div class="entry"><%= post[:body] %></div>
</br>
<div class="byline">
<span class="meta"><%= post[:created_at].strftime("%b %d, %Y") %> Posted By: <%= post.admin_user.name %></span><span class="links"><%= link_to "Read More",post %>
</div>
</div>
<% end %>
分享你的'索引'視圖 –
這意味着,這個文件:app/views/posts/index.html.erb :) – Gerry
我在上面分享了我的索引視圖。 – henrypj