使用inherited_resources测试控制器时出现错误的模型存根

发布于 2024-11-26 13:42:58 字数 769 浏览 1 评论 0原文

我是 RSpec 的新手,我的控制器正在使用继承资源,我有这样的模拟/存根设置:

describe MarketsController do
  def mock_market(stubs={})
    @mock_market ||= mock_model(Market, stubs).as_null_object
  end

  describe "GET index" do
    it "assigns all markets as @markets" do
      Market.stub(:all){ [mock_market] }
      get :index

      assigns(:markets).should eql([mock_market])
    end
  end
end

并且此规范失败,因为分配(:市场)中没有任何内容。我添加后:

class MarketsController
    def index
        @markets = Market.all
    end
end

它会通过,所以我猜这是因为inherited_resources没有调用 Market.all 来获取所有 Market 实例,从而绕过 Market.stub(:全部)。我上面添加的 index 方法显然是多余的,根本不应该存在,所以问题是,在没有显式调用 Market.all 的情况下,我应该在规范中做什么来完成测试?提前致谢!

I'm new to RSpec and my controllers're using inherited_resources, I have this mock/stub setup like:

describe MarketsController do
  def mock_market(stubs={})
    @mock_market ||= mock_model(Market, stubs).as_null_object
  end

  describe "GET index" do
    it "assigns all markets as @markets" do
      Market.stub(:all){ [mock_market] }
      get :index

      assigns(:markets).should eql([mock_market])
    end
  end
end

And this spec fails because there's nothing in the assigns(:markets). After I added:

class MarketsController
    def index
        @markets = Market.all
    end
end

it'll pass so I guess that's because the inherited_resources doesn't call Market.all to get all of the Market instance and thus bypass the stub for Market.stub(:all). The index method I added above is obviously redundant and shouldn't exist at all, so the question is, without call Market.all explicitly, what should I do in my spec to complete the tests? Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦回旧景 2024-12-03 13:42:58

如果我正确读取代码,inherited_resources 首先尝试使用 Market.scoped(如果存在)。那么你有一个范围范围吗?

If I am reading the code correctly, inherited_resources first tries to use Market.scoped if it exists. So do you have a scoped scope?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文