【问题标题】:How to test helper with params如何使用参数测试助手
【发布时间】:2019-08-05 23:01:53
【问题描述】:

我尝试用 params[:a] 测试 helper 中的方法。我没有使用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'

【问题讨论】:

    标签: ruby minitest


    【解决方案1】:

    一个非常通用的方法是使用依赖注入。

    首先,将方法更改为接受参数作为参数:

    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。但是像这样使用依赖注入肯定会起作用,而且更简单一些。

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多