我尝试在代码中测试该方法,但第二个测试返回错误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发布于 2016-06-30 21:43:41
您没有在get请求中传递任何参数,请尝试:
get '/', :index => '1'发布于 2016-07-07 16:11:15
第一个测试起作用,因为在调用get '/'时有一个默认的params映射设置。但是当你直接调用这个方法时,params是nil,这就是为什么你会得到这个错误。这里最好的方法是把你需要的数据发送给你的方法。类似于:
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在请求中查找内容通常在代码的最外层进行。那么你的业务代码也将获得更高的可测试性!
https://stackoverflow.com/questions/38124623
复制相似问题