How to say “any_instance” “should_receive” any number of times in RSpec

后端 未结 7 1909
刺人心
刺人心 2020-12-14 05:24

I\'ve got an import controller in rails that imports several csv files with multiple records into my database. I would like to test in RSpec if the records are actually save

7条回答
  •  眼角桃花
    2020-12-14 05:49

    Here's a better answer that avoids having to override the :new method:

    save_count = 0
    .any_instance.stub(:save) do |arg|
        # The evaluation context is the rspec group instance,
        # arg are the arguments to the function. I can't see a
        # way to get the actual  instance :(
        save_count+=1
    end
    .... run the test here ...
    save_count.should > 0
    

    Seems that the stub method can be attached to any instance w/o the constraint, and the do block can make a count that you can check to assert it was called the right number of times.

    Update - new rspec version requires this syntax:

    save_count = 0
    allow_any_instance_of(Model).to receive(:save) do |arg|
        # The evaluation context is the rspec group instance,
        # arg are the arguments to the function. I can't see a
        # way to get the actual  instance :(
        save_count+=1
    end
    .... run the test here ...
    save_count.should > 0
    

提交回复
热议问题