Created
April 3, 2020 07:10
-
-
Save alexshagov/7ee45690efcf6d25f00f1c85716b978f to your computer and use it in GitHub Desktop.
RSpec basics examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# homework.rb | |
class Homework | |
attr_reader :title, :content, :completed | |
def initialize(title:, content:) | |
@title = title | |
@content = content | |
@completed = false | |
end | |
def valid? | |
return false if title.nil? || content.nil? | |
true | |
end | |
def complete! | |
@completed = true | |
end | |
end | |
# student.rb | |
class Student | |
attr_reader :name | |
def initialize(name:) | |
@name = name | |
end | |
def complete_homework(homework) | |
homework.complete! | |
end | |
end | |
# homework_spec.rb | |
require_relative '../../lib/homework.rb' | |
RSpec.describe Homework do | |
subject { described_class.new(title: title, | |
content: content) } | |
let(:title) { 'title' } | |
let(:content) { 'content' } | |
describe '#valid?' do | |
context 'when title and content are present' do | |
it 'is valid' do | |
expect(subject.valid?).to eq true | |
end | |
end | |
context 'when title is not present' do | |
let(:title) { nil } | |
it 'is not valid' do | |
expect(subject.valid?).to eq false | |
end | |
end | |
context 'when content is not present' do | |
let(:content) { nil } | |
it 'is not valid' do | |
expect(subject.valid?).to eq false | |
end | |
end | |
end | |
describe '#complete!' do | |
it 'sets completed state' do | |
expect { subject.complete! }.to change { subject.completed }.from(false).to(true) | |
end | |
end | |
end | |
# student_spec.rb | |
require_relative '../../lib/student.rb' | |
# NOTE: ideally, you should have 70% unit tests and 30% integration tests | |
RSpec.describe Student do | |
subject { described_class.new(name: name) } | |
let(:name) { 'John Doe' } | |
# unit-like example | |
describe '#complete_homework' do | |
let(:homework) { instance_double('Homework') } | |
it 'sends complete! message to a homework' do | |
expect(homework).to receive(:complete!).once | |
subject.complete_homework(homework) | |
end | |
end | |
# integration-like example | |
describe '#complete_homework' do | |
let(:homework) { Homework.new(title: '1', content: 'c')} | |
it 'sends complete! message to a homework' do | |
expect { subject.complete_homework(homework) }.to change { homework.completed }.from(false).to(true) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment