2016-06-30 4 views
2

メソッドをテストするために、2番目のテストでエラーundefined local variable or method 'params'Minitest:どのように私は私のコードでメソッドをテストしようとしている

メソッドをテストするための正しい方法は何を返していますか?または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 

答えて

1

あなたのGETリクエストを持つ任意のparamsを渡していない、試してみてくださいがあるので

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

これは助けるべきである:http://www.sinatrarb.com/testing.html すべてモック要求メソッドが同じ引数署名有する: GET '/パス'、paramsは= {}、rack_env = {} – SickLickWill

0

間に合わ最初のテストでは、動作します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 

要求で物事を見つけるには、コード内の最外層に行うために、通常は良いです。その後、ビジネスコードも高いテスト容易性を得るでしょう!

関連する問題