describe 'some class name' do
it 'works correctly' do
expect(1 + 1).to eq 2
end
end
Note: describe is used to set up the RSpec test and gives us access to the RSpec DSL it is a function that takes a description and a block (which is the actual test)
class TestClass
def add_one_to(num)
num + 1
end
end
describe TestClass do
it 'works correctly' do
# Setup
class = TestClass.new
# Exercise
result = class.add_one_to(1)
# Verify
expect(result).to eq 2
end
end
class TestClass
def add_one_to(num)
num + 1
end
end
describe TestClass do
it 'works correctly' do
expect(subject.add_one_to(1)).to eq 2
end
end
subject
is an RSpec helper that creates a new object of the class being described
A common practice is to make a test fail by changing the expectation
Note: This also let's us be sure the test will fail if something changes
context
class TestClass
def add_one_to(num)
num + 1
end
end
describe TestClass do
context 'when adding one to one' do
it 'works correctly' do
expect(subject.add_one_to(1)).to eq 2
end
end
end
Note: Like describe and it, context is also a function that takes a description and a block You can also nest contexts and describes as deeply as you'd like It's common to try to make the contexts and describes read well when read together because of how it's ouput from the console
That's what a before
does!
class TestClass
def add_one_to(num)
num + 1
end
end
describe TestClass do
context 'when adding one to one' do
before do
@num = 1
end
it 'works correctly' do
expect(subject.add_one_to(@num)).to eq 2
end
end
end
Note: A before can be used to do more useful things like log in as a user or navigate to a page
Be careful though! Notice how in the context of the spec, we don't know what @num is
it 'works correctly' do
expect(subject.add_one_to(@num)).to eq 2
end
Note: This is called a "Mystery Guest". In this case it's harmless, but imagine if this was line 300+ of a large spec file with lots of let and before blocks.
class TestClass
def add_one_to(num)
num + 1
end
end
describe TestClass do
context 'when adding one to one' do
let(:num) { 1 }
it 'works correctly' do
expect(subject.add_one_to(num)).to eq 2
end
end
end
Note: The difference between let and let! is that the let! will be run no matter what, where regular let isn't evaluated until it's used