[英]Rspec/Rails 4: Failure/Error: visit “/todos” NoMethodError: undefined method `todos' for nil:NilClass in rspec test
[英]Rspec test in rails fails with nilclass error
編輯:這是工作答案:
it "redirects to the show view for the object that was selected" do
object_id = params[:object][:id]
get :select, object: { id: object_id }
expect(subject).to redirect_to object_path(params[:object][:id])
end
我在Rails應用程序中進行了rspec測試,但失敗了,我不知道為什么(rspec noob)。
我不應該使用Factory Girl,所以請不要給出依賴於此的答案。
這是控制器代碼:
def select
redirect_to object_path(params[:object][:id])
end
這是引用從視圖中選擇的集合中選擇的對象:
<%= form_tag select_object_path, method: :get do %>
<%= collection_select(:object, :id, Object.all, :id, :name, prompt: "Select One:") %>
<br>
<%= submit_tag "View Object" %>
<% end %>
測試代碼:
describe "GET #select" do
let(:object) do
Object.create(name: "Object Name", description: "This is an object")
end
let(:params) do
{
object: {
id: "1",
name: "An Object",
description: "Object object"
}
}
end
it "redirects to the show view for the object that was selected" do
object_id = params[:object][:id]
get :select, id: object_id
expect(subject).to redirect_to object_path
end
end
錯誤信息:
Failures:
1) ObjectsController GET #select redirects to the show view for the object that was selected
Failure/Error: redirect_to object_path(params[:object][:id])
NoMethodError:
undefined method `[]' for nil:NilClass
# ./app/controllers/objects_controller.rb:45:in `select'
# ./spec/controllers/objects_controller_spec.rb:100:in `block (3 levels) in <top (required)>'
我嘗試了許多不同的測試,但似乎沒有通過。 似乎認為params [:object] [:id]為nil,但我不知道為什么應該等於1。有人可以解釋我在做什么嗎?
使用了該網站並驗證了該功能似乎可以正常工作,但我只是想不出如何對其進行測試。 參數看起來像這樣:
“對象”=> { “ID”=> “1”}
get :select, id: object_id
您發出GET請求,並傳遞id = 1作為參數。
redirect_to object_path(params[:object][:id])
在select
操作中,您嘗試從object
參數獲取此ID,但沒有發送它。 因此,您調用params[:object]
並得到nil
。 然后調用nil[:id]
並獲取異常。
要解決此問題,請像下面這樣傳遞參數:
get :select, object: { id: object_id }
或直接獲取ID:
redirect_to object_path(params[:id])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.