我在 Controller 中有一个私有(private)方法
private
def body_builder
review_queue = ReviewQueueApplication.where(id: params[:review_queue_id]).first
...
...
end
我只想测试
body_builder
方法,它是一种为 REST 客户端 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
方法,但随后它将中断,因为参数尚未正确设置,因为它们将在对操作的调用中。我总是可以为
body_builder
创建一个条件参数方法,这样它要么接受一个参数,要么使用像 def body_builder(review_queue_id = params[:review_queue_id])
这样的参数然后在测试controller.send(:body_builder, params)
,但我觉得更改代码以使测试通过是错误的,应该按原样进行测试。在将私有(private)方法发送给 Controller 之前,如何将参数输入 Controller ?
最佳答案
我认为你应该可以更换
params = ActionController::Parameters.new({ review_queue_id: @review_queue_application.id })
和
controller.params = ActionController::Parameters.new({ review_queue_id: @review_queue_application.id })
你应该很好。 params 只是 Controller 的一个属性(实际属性是
@_params
,但有一些方法可以访问该 ivar。尝试将 controller.inspect
放在 View 中)。
关于ruby-on-rails - Rails 使用参数测试 Controller 私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37051757/