Stubbing A Model Attribute

2020-07-27 05:41发布

I am writing rspec test for my Cars class, and have a question regarding setting up mocks. I'd like to stub the parts array in Cars, how can i do that?

I have the following code:

class Cars
  has_many :parts

  def heavy_count
    parts.inject(0) { |sum, v| v.weight > 10 ? sum + 1 : sum }
  end
end

With test

context ("#heavy_count") do
  let(:car) {mock_model(Car, :brand => "toyota")}
  let(:vote_1) {mock_model(Part, :weight => 11)}
  let(:vote_2) {mock_model(Part, :weight => 11)}

  it "should return 2 if there are 2 parts heavier than 10" do 
    #how do I stub parts here?
  end
end

1条回答
够拽才男人
2楼-- · 2020-07-27 05:42

Assuming you're using RSpec for mocking and not another framework:

Part.should_receive(:find).and_return([vote_1, vote2])

查看更多
登录 后发表回答