0

我正在编写一个 rspec 测试,在其中循环遍历模型的各种属性以测试是否存在。但是,每当我将变量attr插入循环代码时,它会将 attr 作为属性本身而不是变量读取。我该如何解决?我知道这是可以做到的。

describe "testing the presence" do

  ["title", "url", "post_id"].each do |attr|

    it "tests presence for #{attr}" do
    #attr being recognized as actual model attribute
    link = Link.new(attr: "")
    link.should be_invalid
    link.errors.should_not be_nil

    end

  end

end
4

1 回答 1

1

您可以修改它以使用 symb=>value 的旧语法,例如

describe "testing the presence" do

  ["title", "url", "post_id"].each do |attr|

    it "tests presence for #{attr}" do
    #attr being recognized as actual model attribute
    **link = Link.new(attr.to_sym => "")**
    link.should be_invalid
    link.errors.should_not be_nil
    end
  end
end

您也可能只想向它发送一个方法,例如

link = Link.new
link.send attr.to_sym, ""
于 2012-11-13T23:03:14.087 回答