【问题标题】:How to run arbitrary object method from string in ruby?如何从 ruby​​ 中的字符串运行任意对象方法?
【发布时间】:2010-02-14 02:17:50
【问题描述】:

所以总的来说,我对 ruby​​ 相当陌生,我正在为我正在创建的对象编写一些 rspec 测试用例。许多测试用例都是相当基本的,我只想确保正确填充和返回值。我想知道是否有办法让我使用循环结构来做到这一点。而不必为我要测试的每个方法都设置一个 assertEquals。

例如:

describe item, "Testing the Item" do

  it "will have a null value to start" do
    item = Item.new
    # Here I could do the item.name.should be_nil
    # then I could do item.category.should be_nil
  end

end

但我想要某种方法来使用数组来确定要检查的所有属性。所以我可以做类似的事情

propertyArray.each do |property|
  item.#{property}.should be_nil
end

这个或类似的东西会起作用吗?感谢您提供任何帮助/建议。

【问题讨论】:

    标签: ruby testing rspec


    【解决方案1】:

    object.send(:method_name)object.send("method_name") 可以工作。

    所以你的情况

    propertyArray.each do |property|
      item.send(property).should be_nil
    end
    

    应该做你想做的。

    【讨论】:

    • 谢谢!我知道必须有办法做到这一点。
    【解决方案2】:

    如果你这样做了

    propertyArray.each do |property|
      item.send(property).should be_nil
    end
    

    在单个规范示例中,如果您的规范失败,则很难调试哪个属性不是 nil 或哪些属性失败了。更好的方法是为每个属性创建一个单独的规范示例,例如

    describe item, "Testing the Item" do
    
      before(:each) do
        @item = Item.new
      end
    
      propertyArray.each do |property|
    
        it "should have a null value for #{property} to start" do
          @item.send(property).should be_nil
        end
    
      end
    
    end
    

    这会将您的规范作为每个属性的不同规范示例运行,如果失败,那么您将知道失败的原因。这也遵循每个测试/规范示例一个断言的规则。

    【讨论】:

      【解决方案3】:

      关于Object#send()的几点说明...

      你也可以为方法调用指定参数...

      an_object.send(:a_method, 'A param', 'Another param')
      

      我喜欢使用这种另一种形式__send__,因为“发送”很常见......

      an_object.__send__(:a_method)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-14
        • 2013-03-13
        • 1970-01-01
        • 2010-12-24
        • 1970-01-01
        • 2012-01-30
        • 2013-01-27
        相关资源
        最近更新 更多