如何使用参数测试助手
How to test helper with params
我试图用参数 [:a] 测试助手中的一个方法。我没有使用 Rspec 所以不知道如何解决它。
在辅助文件中:
def get_commands(filter)
order_by = params[:order_by]
something else(filter)
end
和测试文件:
test 'get_commands works' do
filter = something
res = get_commands(filter)
end
显示:NameError: undefined local variable or method `params'
如果我只是添加它也不起作用
params[:order_by]='desc'
一个非常通用的方法是使用依赖注入。
首先,更改接受参数作为参数的方法:
def get_commands(filter, params)
order_by = params[:order_by]
something else(filter)
end
确保在调用该方法时将此新参数包含在控制器中。
然后你可以在你的测试中传递一个模拟参数集:
test 'get_commands works' do
filter = something
mock_params = ActionController::Parameters.new(order_by: :id)
res = get_commands(filter, mock_params)
# ... make your expectation about the result.
end
需要注意的是,依赖注入有时被视为一种反模式。 Rails 确实有一些用于测试控制器的内置助手,请参阅 https://guides.rubyonrails.org/testing.html#functional-tests-for-your-controllers。但是像这样使用依赖注入肯定可以,而且更简单一些。
我试图用参数 [:a] 测试助手中的一个方法。我没有使用 Rspec 所以不知道如何解决它。
在辅助文件中:
def get_commands(filter)
order_by = params[:order_by]
something else(filter)
end
和测试文件:
test 'get_commands works' do
filter = something
res = get_commands(filter)
end
显示:NameError: undefined local variable or method `params'
如果我只是添加它也不起作用
params[:order_by]='desc'
一个非常通用的方法是使用依赖注入。
首先,更改接受参数作为参数的方法:
def get_commands(filter, params)
order_by = params[:order_by]
something else(filter)
end
确保在调用该方法时将此新参数包含在控制器中。
然后你可以在你的测试中传递一个模拟参数集:
test 'get_commands works' do
filter = something
mock_params = ActionController::Parameters.new(order_by: :id)
res = get_commands(filter, mock_params)
# ... make your expectation about the result.
end
需要注意的是,依赖注入有时被视为一种反模式。 Rails 确实有一些用于测试控制器的内置助手,请参阅 https://guides.rubyonrails.org/testing.html#functional-tests-for-your-controllers。但是像这样使用依赖注入肯定可以,而且更简单一些。