To create a new project with rspec, begin from the the project's root directory and install the rspec gem:
gem install rspec
Create a folder in this root directory called spec
where we will house all of your test files. cd
into this folder and create a file called reverser_spec.rb
. Let's write our first test:
describe 'Testing' do
it "should be true" do
expect(true).to be true
end
end
Run the test with the following command:
rspec spec/reverser_spec.rb
This test will pass because you are asserting that true is true (which it is). Let's change the test to call our Reverser
class:
describe 'Reverser' do
it "should reverse a word" do
reverser = Reverser.new
expect(true).to be true
end
end
You should get an error uninitialized constant Reverser
. That's because we haven't created the Reverser
class yet. Go back to the root and create a file called reverser.rb
and create the class:
class Reverser
end
Since you are now trying to refer to a different file, we have to amend the first line of the test file to require_relative '../reverser'
. Try running your test again; it should pass.
Now let's write a more meaningful test:
require_relative '../reverser'
describe 'Reverser' do
it "should reverse a word" do
reverser = Reverser.new
expect(reverser.reverse_word("hello")).to eq "olleh"
end
end
Now run your tests. This error should make sense. You don't have a reverse_word
method in your Reverser
class. Let's add that.
class Reverser
def reverse_word(word)
word.reverse
end
end
Run your tests. You now have a test-driven-developed method!