开发者

Rails - How do you dynamically call the request methods "get put destroy etc" at runtime in tests [duplicate]

开发者 https://www.devze.com 2023-01-02 01:26 出处:网络
This question already has answers here: How to call methods dynamically based on their name? [duplicate]
This question already has answers here: How to call methods dynamically based on their name? [duplicate] (5 answers) Closed 8 years ag开发者_开发知识库o.

I'm always writing tests to check my controller restricts people from certain actions depending on their status i.e. logged in, admin? etc Regardless of whether its a get to :index or a puts to :create the code is always the same. I'm trying to refactor this so that i have one method such as

should_redirect_unauthenticated_to_login_action(request, action)

and call it like so

should_redirect_unauthenticated_to_login_action(:get, :index)  => get :index

But not sure how to dynamically call the various response methods rails provides for functional tests which seem to live in the module ActionController

I mucked around with

module = Kernel.const_get("ActionController")
module::TestProcess.get
NoMethodError: undefined method `get' for ActionController::TestProcess:Module

can anyone help (im very new to dynamic calling in ruby)


This goes in your test helper somewhere, or in any module that you can mix into your functional tests.

def should_redirect_unauthenticated_to_login_action(http_method, action, params = {})
  send http_method, action, params
  should_be_cool_and_stuff # assertions or whatever else goes here.
end


The mapping of a path in combination with the HTTP-Method (get, post, etc.) to a controller and a method is done by the routing, not by the controller itself. So if you want to test what happens after you 'GET' '/users' and maybe want to test for a redirection, IntegrationTest is your thing:

get '/users'
assert_redirected_to :login

Hope this helps


Is Object::send what you're looking for?

As in

2.send(:+, 233) # --> 235
"Cake".send :reverse # --> "ekaC"

Kernel.const_get("A").const_get("B").send :cake; # runs A::B.cake
0

精彩评论

暂无评论...
验证码 换一张
取 消