【问题标题】:Pass instance variable to controller test in rspec?将实例变量传递给rspec中的控制器测试?
【发布时间】:2013-09-07 04:35:55
【问题描述】:

我正在添加以测试现有项目。我有一个用户类,它在创建广告时分配了一个唯一的 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

【问题讨论】:

  • 你使用的是assigns(:guest)而不是assigns(:user)吗?
  • 我都试过了。使用 :user 将我发送到一个 id,但此重定向使用对象 url 而不是 id。
  • 你能发布你的控制器方法吗?
  • 我刚刚得到它。感谢您通过分配让我走上正确的道路。
  • 我知道你解决了这个问题,当然这很好。但是我在这里想为什么该路由使用字符串作为参数而不是 ActiveRecord 对象或哈希...

标签: ruby-on-rails rspec


【解决方案1】:

试试这个:

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) 同名的实例变量。

【讨论】:

  • 我最初使用了与 rspec 书类似的东西。我收到一个错误 ActionController::RoutingError: No route matches {:controller=>"users", :action=>"guest", :url=>nil} 但是谢谢。
  • 嘿,不要这么快就认为测试一定是错误的。你可能有一些路由问题。
  • 测试输出正是我想要的。 (test.host/guest/zaOVsiPBwQ4yNnC0mJNoNA) 但是我写测试的方式,它认为我想要别的东西。
  • 请注意这是assigns(:guest),而不是assigns(:user)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多