IAmAkittycatAMA
IAmAkittycatAMA

Reputation: 245

Minitest: How to test a method

I'm trying to test the method in my code, but the second test is returning the error undefined local variable or method 'params'

What's the correct way to test the method? or is there a change i need to make to how the main.rb is set up?

code:

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

test:

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

Upvotes: 2

Views: 161

Answers (2)

froderik
froderik

Reputation: 4808

Tthe first test works since there is a default params map setup for you when calling get '/'. But when you call the method directly params is nil and that is why you get the error. The best way here is to send in the data you need to you method. Something like:

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

Finding things in the request is normally good to do in the outermost layer in the code. Then you business code will get higher testability also!

Upvotes: 0

SickLickWill
SickLickWill

Reputation: 196

You aren't passing any params with your get request, try:

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

Upvotes: 1

Related Questions