依赖于“当前用户”的单元测试模型逻辑属性
一种常见的情况是应用程序有用户和组,只有作为组管理员的用户才能添加/删除用户。我可能有一个控制器操作“@group.add_member if current_user.is_admin”
似乎测试此行为应该是模型单元测试的一部分,因为它是负责单个任务的一段代码。但我不确定如何最好地包含此方法的正确性取决于控制器的事实。我在想:
- 一种选择是重新定义模型方法,为 current_user 获取额外的参数,但是 这看起来有点难看。
- 另一种选择是仅测试模型中的“add_user”并检查模型中的“is_admin”行为 相反,控制器测试,尽管我认为这是一个模型问题。
- 另一种选择是让此方法成为用户模型的一部分 而不是 Group,因此被调用为: "current_user.add_member_to_group" <-- 听起来像 该功能的责任应该在组模型中 尽管。
想法?
One common case being the app has users and groups, only a user who is an admin of the group can add/remove users. I might have a controller action that goes "@group.add_member if current_user.is_admin"
It seems testing this behavior should be part of the model unit tests., because it's a single piece of code responsible for a single task. But I'm not sure how best to include the fact that this method's correctness depends on the controller. I was thinking:
- One option is to redefine the model method to take an additional param for current_user, but
that seems a bit ugly. - Another option is to test just "add_user" in the model and check 'is_admin' behavior in the
controller test instead, though I was thinking this is a model concern. - Yet another option is to have this method be part of the User model
instead of Group, so to be invoked as: "current_user.add_member_to_group" <-- sounds like the
responsibility for that functionality should be in the Group model
though.
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选项2很好。
逻辑是安全的:
模型对其业务负责
控制器是指挥
Option 2 is fine.
Logic is safe:
the model is responsible for it's business
the controller is the conductor