0

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

我正在关注 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
4

1 回答 1

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

于 2013-09-06T20:03:01.837 回答