V.M
V.M

Reputation: 103

Ruby+Rspec method's arguments sequence check

I try to test method, what will be happen if coming arguments sequence is incorrect. i have already checked for nil parameter. my method accept id, new_name and i want to know what to do when parameters are new_name, id

Hope my question is clear.

Method which i want to test:

def update_recipe(id, new_name)
  raise ArgumentError if id.nil? || new_name.nil?
  recipe = find_recipe_by_id(id).dup
  recipe.name = new_name
  @storage[id] = recipe
  recipe.freeze
end

Here is the rspec code:

context 'when argument sequence is not correct' do
  let(:added_recipe) { subject.add_recipe recipe }

  it 'raises an ArgumentError' do
    expect { subject.update_recipe 'Pasta', added_recipe.id }.to raise_error ArgumentError
  end
end

Upvotes: 0

Views: 118

Answers (1)

nikkypx
nikkypx

Reputation: 2005

You could do something similar to what you did for handling nil based on what you know id or new_name should be. For example, making sure the id is an integer.

def update_recipe(id, new_name)
  raise ArgumentError unless id.is_a? Integer
  raise ArgumentError if id.nil? || new_name.nil?
  recipe = find_recipe_by_id(id).dup
  recipe.name = new_name
  @storage[id] = recipe
  recipe.freeze
end

Upvotes: 1

Related Questions