Stubbing Chained Methods with Rspec

后端 未结 5 1276
醉酒成梦
醉酒成梦 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 23:05

    I figured something out.

    Client.stub!(:named_scope).and_return(@clients = mock([Client]))
    @clients.stub!(:first).and_return(@client = mock(Client))
    

    which allows me to call my controller:

    @client = Client.named_scope(param).first
    

    It works, but is there a better solution?

    EDIT:

    The release of rspec 1.2.6 allows us to use stub_chain meaning it can now be:

    Client.stub_chain(:named_scope, :chained_call).and_return(@clients = [mock(Client)])
    

    This was top of my head, as always check the api for specifics :)

提交回复
热议问题