【发布时间】:2016-04-12 04:10:24
【问题描述】:
我在集成测试中使用存储的会话 return_to URL 时遇到问题。
因为我的控制器可以从不同的地方访问,所以我将引用者存储在 new 操作的会话中,并在我的 create 操作中重定向到它。
cards_controller.rb:
class CardsController < ApplicationController
...
def new
@card = current_user.cards.build
session[:return_to] ||= request.referer
end
def create
@card = current_user.cards.build(card_params)
if @card.save
flash[:success] = 'Card created!'
redirect_to session.delete(:return_to) || root_path
else
render 'new', layout: 'card_new'
end
end
...
end
由于我只在测试中使用 create 操作,因此我想像在单元测试中一样在集成测试中设置会话变量,但它不起作用。我总是被重定向到根路径。
cards_interface_test.rb:
class CardsInterfaceTest < ActionDispatch::IntegrationTest
test 'cards interface should redirect after successful save' do
log_in_as(@user)
get cards_path
assert_select 'a[aria-label=?]', 'new'
name = "heroblade"
session[:return_to] = cards_url
assert_difference 'Card.count', 1 do
post cards_path, card: { name: name, icon: 'white-book', color: 'indigo', contents: 'subtitle | Rogue feature'}
end
assert_redirected_to cards_url
follow_redirect!
assert_match name, response.body
assert_select 'td', text: name
end
end
assert_redirected_to 行上的测试失败。
我试着先打电话给get new_card_path,但没有任何区别,现在我有点迷路了。我不知道这是否应该基本上可以工作,但我犯了一个小错误,或者我是否尝试完全违反最佳实践并且应该重构我的所有接口测试以使用 Selenium 或类似工具之类的东西。
我也尝试提供会话变量作为请求的一部分,就像 rails 指南描述的功能测试一样,没有效果:
post cards_path, {card: { name: name, icon: 'white-book', color: 'indigo', contents: 'subtitle | Rogue feature' }}, {'return_to' => cards_url}
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4