无数据库的RSPEC单元测试
伙计们对我忍受。我非常感谢提供的任何建议。
因此,可以说我有一个具有以下代码的控制器:
class PersonController < ApplicationController
serialize_with personSerializer
string: title
int: age
def update
authorize(person, can_update?)
person.update(title:title,age:age)
serialize person
end
end
因此,就业务逻辑而言,我们在这里:
- 检查授权
- 更新对象
- 返回对象的序列化器(这只是一个JSON结果),
现在我想测试此代码使用RSPEC,但是没有DB可以保存或接收一个对象(嗯,较早的对象,但我想在运行测试时将其删除)。
到目前为止,我已经尝试使用Nulldb Gem删除DB依赖性。但是当无法检索创建对象时,问题到达。
如果我想测试授权(1)。它是另一个GEM的函数,该函数测试用户是否可以使用此控制器。
我需要完全嘲笑它吗?如果是这样,怎么样?哪种工具要使用?
更新相同,如果我做一个人。
Guys bear with me on this. I would highly appreciate any advise provided.
So lets say I have a controller with the below code:
class PersonController < ApplicationController
serialize_with personSerializer
string: title
int: age
def update
authorize(person, can_update?)
person.update(title:title,age:age)
serialize person
end
end
So in terms of Business Logic we have here:
- check for authorize
- update the object
- return the serializer of the object (it's just a json result)
Now I want to test this piece of code with RSpec, but there is no DB to save or receive an object (well there was one earlier, but I want to remove it when running tests).
So far I have tried using nulldb gem to remove the db dependency. But the problem arrives when the created object cannot be retrieved.
If I want to test the authorize (1). It's a function of another gem that tests if the user can even use this controller.
Do I need to completely mock it? If so, how? Which tool to use?
Same for the update, if I do person.update, how should I check if it works if I don't have access to the active record?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非这是系统测试,否则您可能不应该在控制器测试中测试
#authorize
的功能。activerecord#update
也是如此。单元测试应测试您正在测试的代码单元中存在的逻辑,而不是外部依赖项。因此,一个完全可接受的解决方案是断言这些方法是被调用的:如果您仍然想测试生活在第三方库中的业务逻辑,则可以定义隔离所需功能的单独测试:
如果您致力于测试外部功能控制器中的业务逻辑,您需要手动嘲笑第三方库调用的每种方法。我高度推荐这种方法,因为它很
Unless this is a system test, you probably shouldn't be be testing
#authorize
's functionality in your controller tests. Same goes forActiveRecord#update
. Unit tests should test the logic that exists in the unit of code that you are testing, not external dependencies. Therefore a perfectly acceptable solution would be to assert that those methods are called:If you still want to test the business logic that lives in 3rd party libraries, you can define separate tests that isolate the desired functionality:
If you are committed to testing your external business logic in the controller, you'll need to manually mock out every method that the third party library calls. I would highly not recommend this approach as it is
最终,我使用了nulldb,只是嘲笑一切。
还使用了Factroybot。
没有简单的方法,只是努力工作,并嘲笑您需要的所有东西。主要是DB调用。
对于授权部分,我嘲笑使用的策略:
eventually, I used nulldb, and just mock everything.
also used FactroyBot.
There is no easy way to do so, just hard work and mock all the stuff you need. mainly the DB calls.
For the authorize part i mocked the policy used: