如何通过 mocha 和 test/unit 正确存根 Rails 关联方法?

发布于 2024-10-05 19:44:54 字数 966 浏览 0 评论 0原文

我正在开发一个应用程序,其中大多数(如果不是全部)数据的范围都在 current_organization 范围内。因此,在我的控制器中的查找调用中,我有类似这样的事情:

def show
  @user = current_organization.users.find(params[:id])
end

但是,在我的控制器测试中,我很难找出正确的方法(或任何方法)来存根这些调用,以便我可以测试例如:

get :show, :id => 1
assert_response :success

那些失败的说法是“AR 无法找到 ID = 1 且organization_id = 3 的用户”或其他内容。无论我如何尝试,我似乎都无法回避它。

我的设置块看起来像这样:

setup do
  company = organizations(:company) # fixture
  @controller.stubs(:current_organization).returns(company)
  # now what do I stub, if anything?
end

我尝试做类似的事情: company.stubs(:users).returns([users(:one), users(:two)]) 但事实并非如此之所以有效,是因为基本数组不存在 AR find() 调用。

我是否应该将 fake users 数组设置为像 fake_users 这样的变量,然后执行类似 fake_users.stubs(:find).returns(@user) 的操作?感觉不对,但也许这才是正确的方法。

我只是在寻找处理这个问题的最佳方法。我正在使用摩卡和测试/单元,如果这很重要或有帮助的话。

谢谢!

I'm working on an app where most, if not all, of the data is scoped to a current_organization. So in my find calls in my controllers, I have things like this for example:

def show
  @user = current_organization.users.find(params[:id])
end

However, in my controller tests, I'm having a hard time figuring out the proper way (or any way) to stub these calls so that I can test things like:

get :show, :id => 1
assert_response :success

Those are failing saying "AR can't find user with ID=1 and organization_id = 3" or whatever. No matter what I try, I can't seem to get around it.

My setup block looks something like this:

setup do
  company = organizations(:company) # fixture
  @controller.stubs(:current_organization).returns(company)
  # now what do I stub, if anything?
end

I tried doing stuff like: company.stubs(:users).returns([users(:one), users(:two)]) but that doesn't work because the AR find() call doesn't exist for a basic array.

Should I set the fake users array to be a variable like fake_users and then do something like fake_users.stubs(:find).returns(@user)? That didn't feel right, but maybe that's the proper way.

I'm just looking for the best way to handle this. I'm using mocha and test/unit, if that matters or helps.

Thanks!

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

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

发布评论

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

评论(1

酒废 2024-10-12 19:44:54

除非您特别需要访问fake_users,否则我认为您可以做的最简单的事情可能是这样的:-

company.stubs(:users => stub('users', :find => users(:one)))

不幸的是,这种代码很难模拟。您会注意到我建议的解决方案相当脆弱。

Unless you specifically need access to the fake_users, I think the simplest thing you could do is probably something like this :-

company.stubs(:users => stub('users', :find => users(:one)))

Unfortunately, this kind of code is awkward to mock. You will notice that my suggested solution is rather brittle.

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