【问题标题】:Rails, rspec: using "send()" to dynamically generate capybara URLs for controller specsRails,rspec:使用“send()”为控制器规范动态生成水豚 URL
【发布时间】:2015-05-22 15:14:53
【问题描述】:

在#show 动作的控制器规范中:

resource_name = "adoption_transfer_type"

it "returns a single resource" do
  resource = create(resource_name.to_sym)

  # Works
  xhr :get, api_v1_lookups_adoption_transfer_type_path(resource.id)

  # Does not work
  xhr :get, send("api_v1_lookups_#{resource_name}_path(#{resource.id})")
end

这会导致以下错误:

Failure/Error: xhr :get, send("api_v1_lookups_adoption_transfer_type_path(#{resource.id})")
     NoMethodError:
       undefined method `api_v1_lookups_adoption_transfer_type_path(66)'

看起来send(...) 将其转换为字符串文字,而不是作为 Ruby 代码执行,但我认为这是 send(...) 方法的目的。

更广泛的情况是,我正在使用一个规范文件来为多个查找资源生成规范,因为它们都是相同的,而且当我可以同时完成所有这些时,没有理由管理 10 多个文件。

【问题讨论】:

    标签: ruby ruby-on-rails-4 metaprogramming rspec3


    【解决方案1】:

    字符串插入到api_v1_lookups_adoption_transfer_type_path(2),这意味着您正在尝试使用该名称调用某个方法。相反,你想要:

    send("api_v1_lookups_#{resource_name}_path", resource.id)
    

    这是您将参数传递给发送调用的方式,我也会养成使用public_send =) 的习惯

    【讨论】:

    • 这正是我想要的!感谢您的解释;现在我看它是有道理的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    相关资源
    最近更新 更多