【问题标题】:How to stub :where method in Rspec?如何存根:Rspec中的where方法?
【发布时间】:2013-03-01 06:42:05
【问题描述】:

我有以下代码:

Group.where('name ~* ?', params[:name]).first

在这种情况下如何存根where 方法?

Group.stub(:where).and_return(mock_model(Group, name: "SomeName"))

导致错误:

Mock "Group_1001" received unexpected message :first with (no args)

【问题讨论】:

    标签: ruby-on-rails ruby rspec stub


    【解决方案1】:

    在您的情况下,您应该返回响应 first 的内容。数组是一个不错的选择。

    Group.stub(:where).and_return([mock_model(Group, name: "SomeName")])
    

    【讨论】:

      【解决方案2】:

      您可以使用stub_chain 存根wherefirst,然后返回您的对象:

      Group.stub_chain(:where, :first).and_return(mock_model(Group, name: "SomeName"))
      

      【讨论】:

        猜你喜欢
        • 2015-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-03
        • 2015-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多