【发布时间】:2017-09-27 04:44:27
【问题描述】:
想象一下有一个控制器集成测试调用一个控制器方法的场景,其中cookie.signed 用于一些完整性检查。
控制器
# app/controllers/foo_controller.rb
def index
entity = FooEntity.find_by_id(params[:id])
if entity.nil?
raise ActionController::BadRequest, 'Could not find requested entity.'
else
@is_authorized = entity.token == cookies.signed[:token]
if @is_authorized
# Success! The path to be tested.
else
raise ActionController::BadRequest, 'Unauthorized cookie token.'
end
end
end
控制器测试
# app/test/controllers/foo_test.rb
require 'test_helper'
class FooControllerTest < ActionDispatch::IntegrationTest
test 'should be working' do
cookies.signed[:token] = '7e5201169ef160e31058d2a1976a5552'
get '/foobar/123'
end
end
但是,我不确定如何在测试中设置cookie.signed。上面的测试代码抛出异常:
NoMethodError: Rack::Test::CookieJar:0x007fe90965ccd8 的未定义方法“签名”
试图寻找解决方案,但我能找到的最接近的是这篇文章,https://sikac.hu/reconstruct-a-cookie-jar-and-read-signed-cookie-in-capybara-f71df387f9ff,但无法弄清楚如何构造 ActionDispatch::Request 对象。
【问题讨论】:
标签: ruby-on-rails unit-testing cookies ruby-on-rails-5