我正在尝试向控制器测试PUT请求,但我需要向操作发送GET和POST正文。 params不能拼凑在一起,因为代码的某些部分明确地访问GET参数。
你如何将GET参数传递给put动作?
我有这个测试:
it "updates the account password to the provided value" do
put(:update, @params)
@account.reload.crypted_password.should == PasswordAccount.encrypt(@newpass, @account.password_salt)
end
如何在发送到操作的查询字符串中添加“令牌”参数?
答案 0 :(得分:3)
put
方法在Rails'ActionController::TestCase::Behavior
:
http://api.rubyonrails.org/classes/ActionController/TestCase/Behavior.html#method-i-put
从我所看到的,不支持分离不同的get / post params,但为什么不将它包含在@params
变量中呢?
put(:update, @params.merge(:token => 'gobbledygook'))
当你的代码看到params时,无论如何Rails已经为你合并了get / post params。
HTH, 大卫
答案 1 :(得分:1)
更新:
在调查了rails测试源代码之后,我想出了以下内容:
def process_with_query(action, query_string="", parameters = nil, session = nil, flash = nil, http_method = 'GET')
# Sanity check for required instance variables so we can give an
# understandable error message.
%w(@routes @controller @request @response).each do |iv_name|
if !(instance_variable_names.include?(iv_name) || instance_variable_names.include?(iv_name.to_sym)) || instance_variable_get(iv_name).nil?
raise "#{iv_name} is nil: make sure you set it in your test's setup method."
end
end
@request.recycle!
@response.recycle!
@controller.response_body = nil
@controller.formats = nil
@controller.params = nil
@html_document = nil
@request.env['REQUEST_METHOD'] = http_method
parameters ||= {}
@request.assign_parameters(@routes, @controller.class.name.underscore.sub(/_controller$/, ''), action.to_s, parameters)
@request.session = ActionController::TestSession.new(session) unless session.nil?
@request.session["flash"] = @request.flash.update(flash || {})
@request.session["flash"].sweep
@controller.request = @request
@controller.params.merge!(parameters)
build_request_uri(action, parameters)
@request.env["QUERY_STRING"] = query_string.kind_of?(Hash) ? query_string.to_param : query_string
@request.env["action_dispatch.request.query_parameters"] = Rack::Utils.parse_query(@request.env["QUERY_STRING"])
ActionController::Base.class_eval { include ActionController::Testing }
@controller.process_with_new_base_test(@request, @response)
@request.session.delete('flash') if @request.session['flash'].blank?
@response
end
def put_with_query(action, query_string="", parameters=nil, session=nil, flash=nil)
process_with_query(action, query_string, parameters, session, flash, 'PUT')
end
def post_with_query(action, query_string="", parameters=nil, session=nil, flash=nil)
process_with_query(action, query_string, parameters, session, flash, 'POST')
end
有任何意见吗?