【问题标题】:Dynamic method call in routes spec路由规范中的动态方法调用
【发布时间】:2013-01-07 06:27:09
【问题描述】:

我正在我的 Rails 3.2 应用程序中使用 rspec 测试对我的路由的简单获取请求。由于都是 get 请求,并且都只是具有与视图名称相似的不同 action 名称,因此为每个 get 请求手动编写不同的测试确实是重复的。

相反,我想提出这样的想法:

%(action_1 action_2 action_3 action_4).each do |action|
    it "routes to the #{action} page" do
        get("liver_diseases#{action}_path").should route_to("liver_diseases##{action}")
    end
end

这个伪代码失败了:get("liver_diseases_#{action}_path") 所以我需要做的是一个动态方法调用——但就我所发现的而言,这将涉及.send(:method_name),我需要知道类名。我找不到那个。

我需要做什么才能使这个方法调用起作用?

【问题讨论】:

    标签: ruby-on-rails dynamic methods rspec


    【解决方案1】:

    这将涉及 .send(:method_name),为此我需要知道 类名

    当接收者丢失时,它总是self。在控制器示例的上下文中,self 应该是控制器实例。因此,您应该能够通过以下方式获得该路径:

    send "liver_diseases_#{action}_path"
    

    应该相当于:

    controller.send "liver_diseases_#{action}_path"
    

    【讨论】:

    • 对于@Charles 的特定需求:get(send("hello_world#{action}_path").should 等将起作用。
    猜你喜欢
    • 1970-01-01
    • 2017-12-20
    • 2022-12-16
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多