Victor
Victor

Reputation: 45

Iterating over certain model attributes with RSpec

I'm learning tests in Rails with RSpec and I'm trying to refactor some basic unit tests.

I have a model with :name, :protein and :calories. I would like to write a .each do loop that would loop only through some of the attributes (:protein and :calories), set a negative value to them and then test them.

Right now I'm writing duplicate code

  it "is not valid with negative values" do
    subject.calories = -1
    expect(subject).to_not be_valid
  end

  it "is not valid with negative values" do
    subject.protein = -1
    expect(subject).to_not be_valid
  end

As there are actually several attributes I would like to be able to write something like

nutritional_value = [:protein, :calories]
  nutritional_value.each do |nutr|
    subject.nutr = -1
    expect(subject).to_not be_valid
  end

Hope I've made myself clear, still learning

Upvotes: 0

Views: 139

Answers (2)

Nick M
Nick M

Reputation: 2532

I am not sure what your model attributes are (can you post them?) but if your model has the fields "protein" and "calories" and you validate these to be > -1 you probably want to:

  [:protein, :calories].each do |nutr|
    subject[nutr] = -1
    expect(subject).to_not be_valid
  end

Also if you have two different validations defined in your model, it's better practice to spec them in two separate examples if you absolutely want to do it by the book.

Upvotes: 0

Mateo977
Mateo977

Reputation: 103

It is not best practices to write logic in spec file. Install shoulda matchers gem (https://github.com/thoughtbot/shoulda-matchers) And then you can write like this

it { is_expected.not_to allow_value(-1).for(:protein) }
it { is_expected.not_to allow_value(-1).for(:calories) }

Upvotes: 1

Related Questions