rails中的Rspec测试失败,出现nilclass错误

时间:2015-12-29 04:52:52

标签: ruby-on-rails rspec

编辑:这是工作答案:

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

这是引用从视图中的集合select中选择的对象:

<%= 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]是零,但我无法弄清楚为什么它应该等于1.有人可以解释我做错了什么吗?

使用过网站并验证功能似乎有效,但我无法弄清楚如何测试它。 params看起来像这样:

“对象”=&GT; { “ID”=&gt; “中1”}

1 个答案:

答案 0 :(得分:3)

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])