To create a new project with rspec, begin from the the project's root directory and install the rspec gem:
gem install rspecCreate 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
endRun the test with the following command:
rspec spec/reverser_spec.rbThis 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
endYou 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
endSince 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
endNow 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
endRun your tests. You now have a test-driven-developed method!