Ruby 在rspec中测试依赖于请求主体的private-before过滤器
我有以下控制器:Ruby 在rspec中测试依赖于请求主体的private-before过滤器,ruby,http,rspec,ruby-on-rails-3.2,metaprogramming,Ruby,Http,Rspec,Ruby On Rails 3.2,Metaprogramming,我有以下控制器: class ApiController < ApplicationController before_filter :authenticate_user_from_token! private def authenticate_user_from_token! @json = JSON.parse(request.body.read) --auth logic goes here extracting user credentia
class ApiController < ApplicationController
before_filter :authenticate_user_from_token!
private
def authenticate_user_from_token!
@json = JSON.parse(request.body.read)
--auth logic goes here extracting user credentials goes here--
request.body.rewind
if auth_valid
authenticate
else
render nothing: true, status: :unauthorized
end
end
end
这里的缺陷是,我不确定如何模拟request.body以包含有效/无效凭据。我尝试了以下方法:
before do
class Hash
def body
self['body']
end
end
@request = {}
@request['body'] =StringIO.new({auth_goes_here}.to_json)
end
但是,在方法中,请求仍然会被一个全新的ActionController::TestRequest覆盖。
2) 直接投寄:
@controller.send(authenticate_user_from_token!)
before do
post :authenticate_user_from_token!, my_preconstructed_credentials, format: :json
end
其结果是:
*** AbstractController::ActionNotFound Exception: The action 'authenticate_user_from_token!' could not be found for ApiController
3) 在运行时定义公开的方法:
before do
@controller.class_eval <<-RUBY_EVAL
public
def update
end
RUBY_EVAL
end
在做之前
@controller.class_eval最后,以下各项起到了作用:
before do
class ::TestApiController < ApiController
def hello
render nothing: true
end
end
Rails.application.routes.draw do
match 'hello', to: 'test_api#hello'
end
@controller = TestApiController.new
@request.env['RAW_POST_DATA'] = my_awesome_json
post :hello
end
在做之前
类::TestApiController