ruby-on-rails – Rails测试控制器私有方法与params

我在控制器中有一个私有方法

private 
  def body_builder
    review_queue = ReviewQueueApplication.where(id: params[:review_queue_id]).first
    ...
    ...
  end

我想测试一下body_builder方法,它是一个为剩余客户端api调用补充有效负载的方法.但它需要访问参数.

describe ReviewQueueApplicationsController, type: :controller do
  describe "when calling the post_review action" do
    it "should have the correct payload setup" do
      @review_queue_application = ReviewQueueApplication.create!(application_id: 1)
      params = ActionController::Parameters.new({ review_queue_id: @review_queue_application.id })
      expect(controller.send(:body_builder)).to eq(nil)
    end
  end
end

如果我运行上面的内容,它将发送body_builder方法,但之后它会中断,因为params没有正确设置,因为它们将在对动作的调用中.

我总是可以为body_builder方法创建一个条件参数,这样它就可以接受一个参数,或者它将使用para这样的def body_builder(review_queue_id = params [:review_queue_id])然后在测试controller.send(:body_builder,params)中使用),但我觉得更改代码以使测试通过是错误的,它应该只是按原样测试它.

在将私有方法发送给控制器之前,如何将参数传入控制器?

最佳答案 我认为你应该能够取代

params = ActionController::Parameters.new({ review_queue_id: @review_queue_application.id })

controller.params = ActionController::Parameters.new({ review_queue_id: @review_queue_application.id })

你应该好. params只是控制器的一个属性(实际属性是@_params,但有一些方法可以访问ivar.尝试将controller.inspect放在视图中).

点赞