0

我有一个 Rails 控制器,我想测试一个方法test_method

class ActiveController < ActionController::Base
  def test_method
    user = acc_users.all_users.find params[:id]
    if !user.active?
      user.call_method!
    end
  end
end

我必须测试call_method没有被调用。这是我想出的,但我认为这不会奏效。

 it "should not call call_method" do
    u = user(@acc)
    put :test_method, :id => u.id
    expect(u).not_to have_received(:call_method!)
  end

在这里关注了这个问题,发现它几乎相似,只是被调用的方法在另一个类中。当我尝试上面的代码时,我收到一条错误消息,例如“预期对象要响应has_received?

我相信我将无法使用给定的设置对此进行测试,因为用户没有被注入test_method.

call_method是对将作业排入队列的方法的调用,因此我想确保它不会被调用。

我将如何测试这种方法?

4

1 回答 1

0

您可以在模型上使用expect_any_instance_of方法,User计数为“n”,以测试模型是否接收特定方法“n”次。

此外,您必须在实际调用您的操作之前设置此期望,因为期望基于操作本身内部发生的事情,而不是操作返回的事情。

user假设您的变量是 class 的一个实例,则以下行应该有效User

u = user(@acc)
expect_any_instance_of(User).to receive(:call_method!).once
put :test_method, :id => u.id

或者,您可以将规范更改为像黑盒一样运行,而不是测试特定方法的调用。例如,您可以模拟call_method!以始终返回一个值,然后在可能的情况下根据该值继续您的测试。这可以使用expect_any_instance_of(User).to receive(:call_method!).and_return(<some_object>). 稍后可以假设您的测试根据您设置的值运行。此替代解决方案只是一个建议,它可能无法根据您的特定需求工作。

于 2019-10-29T16:37:39.683 回答