Heisenberg Heisenberg - 3 months ago 10
Ruby Question

How to loop over an attribute of a subject in RSpec?

Is it possible to loop through the subject attribute like so:

subject { assignment }

its(:submissions).each do |submission|
submission.grade should eq 100
end


The error I got was that
Undefined method each for Class ...


I also tried

subject { assignment }
its(:submissions) do
each do |submission|
submission.grade should eq 100
end
end


and get


undefined method `each' for
RSpec::Core::ExampleGroup::Nested_4::Nested_4::Nested_1::Nested_1:0x00000005f91ac8

Answer

You can get the subject back in an example with the subject method. So you can do what you want this way:

subject { assignment }
it "has some number of submissions, each with a grade of 100" do
  subject.submissions.each { |submission| submission.grade.should eq 100 }
end

Side note: Explicitly using subject makes your tests harder to read. Instead, use let:

let(:assignment) { create :assignment } # or whatever is necessary to create the assignment
it "has some number of submissions, each with a grade of 100" do
  assignment.submissions.each { |submission| submission.grade.should eq 100 }
end
Comments