thank_you
thank_you

Reputation: 11107

Variable passed in with each method being treated as attribute for model

I'm writing a rspec test where I loop through various attributes of a model to test for presence. However, whenever I insert the variable attr into the looped through code, it reads attr as an attribute itself and not a variable. How do I fix this? I know this can be done.

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

Upvotes: 0

Views: 57

Answers (1)

Yuriy Goldshtrakh
Yuriy Goldshtrakh

Reputation: 2014

You can modify it to use old syntax of symb=>value such as

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

also you might just want to send a method to it such as

link = Link.new
link.send attr.to_sym, ""

Upvotes: 1

Related Questions