【问题标题】:Minitest: How to test a methodMinitest:如何测试方法
【发布时间】:2016-11-02 15:19:45
【问题描述】:

我正在尝试在我的代码中测试该方法,但第二个测试返回错误undefined local variable or method 'params'

测试方法的正确方法是什么?或者我需要对main.rb 的设置方式进行更改吗?

代码:

require 'sinatra'
require 'sinatra/reloader'


def get_products_of_all_ints_except_at_index()
  @array = [1, 7, 3, 4]
  @total = 1
  @index = params[:index].to_i
  @array.delete_at(@index)
  @array.each do |i|
    @total *= i
  end
end



get '/' do
  get_products_of_all_ints_except_at_index
  erb :home
end

测试:

ENV['RACK_ENV'] = 'test'

require 'minitest/autorun'
require 'rack/test'

require_relative 'main.rb'

include Rack::Test::Methods

def app
  Sinatra::Application
end

describe 'app' do
  it 'should return something' do
    get '/'
    assert_equal(200, last_response.status)
  end

  it 'should return correct result' do
    get_products_of_all_ints_except_at_index
    assert_equal(24, @total)
  end
end

【问题讨论】:

    标签: ruby sinatra minitest


    【解决方案1】:

    您没有通过 get 请求传递任何参数,请尝试:

    get '/', :index => '1'
    

    【讨论】:

    • 这应该会有所帮助:sinatrarb.com/testing.html 所有模拟请求方法都具有相同的参数签名:get '/path', params={}, rack_env={}
    【解决方案2】:

    第一个测试有效,因为在调用 get '/' 时为您提供了默认的 params 地图设置。但是当您直接调用该方法时,paramsnil,这就是您收到错误的原因。这里最好的方法是将您需要的数据发送给您的方法。类似的东西:

    def get_products_of_all_ints_except_at_index index
      @array = [1, 7, 3, 4]
      @total = 1
      @array.delete_at(index)
      @array.each do |i|
        @total *= i
      end
    end
    
    get '/' do
      get_products_of_all_ints_except_at_index params[:index].to_i
      erb :home
    end
    

    在请求中查找内容通常最好在代码的最外层进行。那么您的业务代码也会获得更高的可测试性!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 2022-11-30
      相关资源
      最近更新 更多