传入的变量将每个方法视为模型的属性

时间:2012-11-13 22:48:57

标签: ruby-on-rails ruby rspec

我正在写一个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

1 个答案:

答案 0 :(得分:1)

您可以将其修改为使用symb =>值的旧语法,例如

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, ""