将实例变量传递给rspec中的控制器测试?

时间:2013-09-06 19:45:36

标签: ruby-on-rails rspec

我正在添加测试现有项目。我有一个在创建广告上分配了唯一网址的用户类,然后被重定向到包含该网址的路径。

我正在关注rspec书并编写了这个测试

it 'redirects to users#show' do
  post :create, user: attributes_for(:guest)
  expect(response).to redirect_to guest_path(:guest)
end

我在运行测试时得到了这个。

Expected response to be a redirect to <http://test.host/guest/guest> but was a redirect to <http://test.host/guest/h7gutr1CMYxa5VNgWH5l1A>

控制器发送回的重定向是正确的,但我显然是错误地写了测试。如何改变通过测试的期望?

编辑:离得更近了,但仍然没有。使用

expect(response).to redirect_to guest_path(assigns(:user))

给出:

Expected response to be a redirect to <http://test.host/guest/1> but was a redirect to <http://test.host/guest/zaOVsiPBwQ4yNnC0mJNoNA>

使用:

expect(response).to redirect_to guest_path(assigns(:user))

给出:

NoMethodError:
   undefined method `url' for :user:Symbol

解决方案:

我无法弄清楚如何在实例变量上调用方法。这是这样做的:

it 'redirects to users#show' do
  post :create, user: attributes_for(:guest)
  expect(response).to redirect_to guest_path(assigns(:user).url)
end

1 个答案:

答案 0 :(得分:2)

试试这个:

it 'redirects to users#show' do
  post :create, user: attributes_for(:guest)
  expect(response).to redirect_to guest_path(assigns(:guest))
end

在这种情况下,assigns(:guest)将等于与您正在测试的请求返回的参数(:guest)同名的实例变量。