Skip to content

Instantly share code, notes, and snippets.

@serradura
Last active December 6, 2020 19:09
Show Gist options
  • Save serradura/8d2ef8dfd7c9a71e467b7461f58fa70c to your computer and use it in GitHub Desktop.
Save serradura/8d2ef8dfd7c9a71e467b7461f58fa70c to your computer and use it in GitHub Desktop.
Exemplos de testes com rspec
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'rspec', '~> 3.10'
end
module Calc
extend self
def add(a, b); number(a) + number(b); end
def sub(a, b); number(a) - number(b); end
private
def numeric_string?(value)
value.is_a?(String) && value =~ /((\d+)?\.\d|\d+)/
end
def number(value)
return value if value.is_a?(Numeric)
return value.include?('.') ? value.to_f : value.to_i if numeric_string?(value)
raise TypeError, 'the value must be Numeric or a String with numbers'
end
end
require 'rspec/autorun'
RSpec.describe Calc do
describe '.add' do
context 'with numeric values' do
it 'returns the sum of the values' do
expect(Calc.add(1, 1)).to eq(2)
expect(Calc.add(1.5, 1)).to eq(2.5)
end
end
context 'with string values' do
context 'and all of them are numbers' do
it 'returns the sum of the values' do
expect(Calc.add(1, '1')).to eq(2)
expect(Calc.add('1.5', 1)).to eq(2.5)
end
end
context "and some of them isn't a number" do
it 'raises an error' do
expect { Calc.add('a', 1) }.to raise_error(TypeError)
end
end
end
context 'with some invalid argument' do
it 'raises an error' do
expect { Calc.add([], '1') }.to raise_error(TypeError)
expect { Calc.add('1.5', {}) }.to raise_error(TypeError)
end
end
end
end
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'rspec', '~> 3.10'
end
module Calc
extend self
def add(a, b); number(a) + number(b); end
def sub(a, b); number(a) - number(b); end
private
def numeric_string?(value)
value.is_a?(String) && value =~ /((\d+)?\.\d|\d+)/
end
def number(value)
return value if value.is_a?(Numeric)
return value.include?('.') ? value.to_f : value.to_i if numeric_string?(value)
raise TypeError, 'the value must be Numeric or a String with numbers'
end
end
require 'rspec/autorun'
RSpec.describe Calc do
describe '.add' do
context 'with numeric values' do
it { expect(Calc.add(1, 1)).to eq(2) }
it { expect(Calc.add(1.5, 1)).to eq(2.5) }
end
context 'with string values' do
context 'and all of them are numbers' do
it { expect(Calc.add(1, '1')).to eq(2) }
it { expect(Calc.add('1.5', 1)).to eq(2.5) }
end
context "and some of them isn't a number" do
it { expect { Calc.add('a', 1) }.to raise_error(TypeError) }
end
end
context 'with some invalid argument' do
it { expect { Calc.add([], '1') }.to raise_error(TypeError) }
it { expect { Calc.add('1.5', {}) }.to raise_error(TypeError) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment