简体   繁体   English

如何使用 Minitest 对私有方法进行单元测试

[英]How to unit test a private method using Minitest

I wanted to test a private method but I came across an answer that states simply YOU DONT!我想测试一个私有方法,但我遇到了一个简单地说你不这样做的答案!

How can I refactor this code so that I can test it?我怎样才能重构这段代码以便我可以测试它?

In my controller, I have a private method在我的controller里面有一个私有方法

 def move_employees
    return unless params[:store_id].present?
    store = scope.find(params[:store_id])
    store.employments << @store.employments
    store.save!
 end

This method is called inside the destroy action such that when I want to delete a store that has employees, I can move them over to an existing store picked from an drop down menu此方法在 destroy 操作中调用,这样当我想删除有员工的商店时,我可以将他们移动到从下拉菜单中选择的现有商店

def destroy
    @store = scope.find(params[:id])
    authorize([:manage, :settings, @store])
    if @store.destroy
        move_employees
...

I am thinking of moving the method to the model, but I am not sure if that is the best approach, and also, I don't know how I would then test it.我正在考虑将该方法移至 model,但我不确定这是否是最佳方法,而且,我也不知道我将如何测试它。

What is the best practice in this case?在这种情况下,最佳做法是什么?

Thank you.谢谢你。

Philosophically, you shouldn't, as private methods are expected to be tested in the context of the public code.从哲学上讲,您不应该这样做,因为私有方法应该在公共代码的上下文中进行测试。 For example, if move_employees must be called as part of destroy , test the end state, not the mechanism to get there.例如,如果move_employees必须作为destroy的一部分调用,则测试结束 state,而不是到达那里的机制。 That is, assert that after deletion the employees are correctly moved.也就是说,断言删除后员工已正确移动。

Practically you can test directly if you're prepared to bust out send .实际上,您可以直接测试是否准备好send This more direct method of testing can be useful for particularly complex implementations, but in those cases you should probably separate your concerns and have some other tool that facilitates that operation which does have a public interface.这种更直接的测试方法对于特别复杂的实现可能很有用,但在这些情况下,您可能应该分开您的关注点,并拥有一些其他工具来促进该操作,这些工具确实具有公共接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM