如何在RSpec中循环一个主题的属性?

时间:2014-06-09 16:41:50

标签: ruby rspec

是否可以像这样遍历主题属性:

subject { assignment }

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

我得到的错误是Undefined method each for Class ...

我也试过

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

并获取

  

未定义的方法`每个'对于   RSpec的::核心:: ExampleGroup :: Nested_4 :: Nested_4 :: Nested_1 :: Nested_1:0x00000005f91ac8

1 个答案:

答案 0 :(得分:1)

您可以使用subject方法返回一个示例中的主题。所以你可以这样做你想做的事情:

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

旁注:Explicitly using subject makes your tests harder to read.而是使用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