Stubbing Chained Methods with Rspec

后端 未结 5 1203
醉酒成梦
醉酒成梦 2021-02-05 22:06

I want to call a named_scope that will only return one record, but the named_scope returns an array, that\'s not a big deal as I can just chain it with .first:

M         


        
5条回答
  •  不要未来只要你来
    2021-02-05 22:58

    The question is quite old and hence there are few enhancements in how stubbing can be done. Now you can use stub_chain method to stub a chain of method calls. For example:

    @client = Client.named_scope(param).first

    can be stubbed with:

    Client.stub_chain(:named_scope,:first).and_return(@client = mock(Client))

    More examples of stub_chaining:

    describe "stubbing a chain of methods" do
      subject { Object.new }
    
      context "given symbols representing methods" do
        it "returns the correct value" do
          subject.stub_chain(:one, :two, :three).and_return(:four)
          subject.one.two.three.should eq(:four)
        end
      end
    
      context "given a string of methods separated by dots" do
        it "returns the correct value" do
          subject.stub_chain("one.two.three").and_return(:four)
          subject.one.two.three.should eq(:four)
        end
      end
    end
    

    or please have a look at:

    Long live the rspecs!!! :)

提交回复
热议问题