Home Ruby Tutorial Ruby Tutorial: Rspec

Ruby Tutorial: Rspec

159
0
SHARE
Ruby Tutorial Rspec
Ruby Tutorial Rspec

In this Ruby tutorial, we will cover about Rspec. Rspec is a testing framework for Ruby. If you are a software developer then you must have already done some testing before. For example, you might create a HTML form and input the data and check and see if the form when submitted is saves successfully to the database or if proper validation is applied. But this is a manual testing. It can be tedious and repetitive. Every time you make a change to your components, you will have to test it again manually. So now we are talking about testing because we are going to write a code to test other code. Rspec stands for Ruby Specification. It uses Domain Specific Language(DSL). It means Rspec has its own way of doing things and we will have to talk to Rspec in its own language and not just in Ruby. I recommend learning Ruby before Rspec because we need to learn to write code before we can actually test it.

Note that Rails is not required for Rspec. We can test plain Ruby code with Rspec. Later after you understand how to test Ruby code, you can start testing controllers and models of Rails.

 

Installation

Ruby >=1.8.7 is required for installing Rspec. Ruby and RubyGem are required before installing Rspec. Make sure you have both by the following command.

$ ruby -v

$ gem -v

 

Enter the command below to install the gem

$ gem install rspec

 

It actually installs five gems for us as the dependencies.They are Rspec, Rspec Core, Rspec Expectations, Rspec Mocks and Rspec Support. All these gems work together with Rspec. Check if Rspec installed successfully.

$ rspec –version

$ rspec –help

 

If you interested to build your own gem you can read Ruby Tutorial: Building Your Own Ruby Gem

Now let’s write our first ruby class and test it with Rspec. Make a file called car_spec.rb. For the first example I want to make it simple. Let’s write the spec and ruby class on same file though in real example we create different files.We will see them later.

class Car

  def greet

“Hello I am a car”

  end

end

 

describe Car do

 context “When testing the car class” do

 

   it “should greet when we call greet method” do

      my_car = Car.new

      message = my_car.greet

      expect(message).to eq(“Hello I am a car”)

 

    end

 

 end

 

end

 

Now run this spec by the following command.

$ rspec car_spec.rb

.

 

Finished in 0.00212 seconds (files took 0.12301 seconds to load)

1 example, 0 failures

 

 

Now you must see the green signal meaning you passed the test. Your class is returning the output in the way it was supposed to.

Now, let’s look the Rspec code carefully. We see it looks like Ruby but not like Ruby at same time. Let me describe some keywords first.

 

describe keyword:

It is used to define the group of examples or tests. This keyword can take the name of class or string as the argument.In above example we took name of class as the argument. We need to pass a block to the describe which contains the individual tests. The block goes inside the do..end keywords.

 

context keyword:

This is similar to describe keyword but one thing to remember is context keyword wraps the similar types of tests but describe keyword may not. It also contains a parameter and it can be either a string or a class name. It is not compulsory but recommended.

 

it keyword:

This keyword is used to describe an “Example”. By example, we mean a test or test case. It also contains block. The block contains the rest of the code to test the behaviour of class.

 

expect keyword:

It is used to define an “Expectation” in Rspec. This keyword is used to verify if the expected condition has been met.

 

Matchers In Rspec

These are the keywords used in Rspec to verify the result obtained from the class to the one we define. In our example above we had

expect(message).to eq(“Hello I am a car”)


Here the keyword eq is a matcher. We have different types of matchers, so let’s go through them one by one briefly.

 

Equality/Identity Matchers

=> eq, eql, be, equal

Let’s understand them by example.

describe “Equality Matchers” do

 

  it “should show how the equality Matchers work” do

     my_string = “roses”

     another_string = my_string

     

    # These Expectations will all pass

 

     expect(my_string).to eq “roses”

     expect(my_string).to eql “roses”

     expect(my_string).to be another_string

     expect(my_string).to equal another_string

  end

  

end

 

 

Comparison Matchers

=> <, >, <=, >= , be_between_inclusive, be_between_exclusive, match

Example

describe “Comparison Matchers” do

 

  it “should show how the comparison Matchers work” do

     num1 = 1

     num2 = 2

     num3 = 3

     string = ‘test string’

     

     # The following Expectations will all pass

     expect(num2).to be > num1

     expect(num1).to be >= num1

     expect(num1).to be < num2

     expect(num2).to be <= num2

     expect(num3).to be_between(1,3).inclusive # Include 1 and 3

     expect(num2).to be_between(1,3).exclusive  # Exclude 1 and 3

     expect(string).to match /TEST/i #regex

  end

  

end

 

 

Class/Type Matchers

=> be_instance_of, be_kind_of, respond_to

describe “Type/class Matchers” do

  it “should show how the type/class Matchers work” do

     x = 40

     y = 90.44

     z = ‘the string’

     

     # Following Expectations will all pass

     expect(x).to be_instance_of Fixnum

     expect(y).to be_kind_of Numeric

     expect(z).to respond_to(:length)

  end

  

end

 

 

True/False Matchers:

=> be true, be false, be_truthly, be_falsey, be_nil

describe “Example of the true/false/nil Matchers” do

  it “should show how the true/false/nil Matchers work” do

     first = true

     second = false

     third = nil

     str = “test string”

     

     # The following Expectations will all pass

     expect(first).to be true

     expect(second).to be false

     expect(str).to be_truthy

     expect(third).to be_falsey

     expect(third).to be_nil

  end

end

 

 

Error Matchers:

Let’s see this by example

describe “Example of the error Matchers” do

  it “should show how the error Matchers work” do

     

     # The following Expectations will all pass

     expect { 100/0 }.to raise_error(ZeroDivisionError)

     expect { 100/0 }.to raise_error(“divided by 0 error”)

     expect { 100/0 }.to raise_error(“divided by 0”, ZeroDivisionError)

  end

end

 

 

Test Doubles:

They are also known as Rspec Mocks.A double is an object that can replace the object if that does not exist or so. For example, we have a method in a Ruby class that calls to another class for getting data but the class that gets called does not exist yet or we have not written yet. Then in such case we need to use doubles.

Example

class Hospital

  def initialize(patients)

     @patients = patients

  end

  

  def list_patients_names

     @patients.map(&:name).join(‘,’)

  end

end

 

describe Hospital do

  it ‘the list_patients_names method should work correctly’ do

     patient1 = double(‘patient’)

     patient2 = double(‘patient’)

     

     allow(patient1).to receive(:name) { ‘John Doe’}

     allow(patient2).to receive(:name) { ‘Hero Smith’}

     

     hs = Hospital.new [patient1,patient2]

     expect(hs.list_patients_names).to eq(‘John Doe,Hero Smith’)

  end

end

In the example above we created the doubles so that the test when run they will pass.

 

Conclusion:

Rspec is a one level difficult than what Ruby is. To have strong foundation of Rspec, you will need to be proficient with Ruby. When you get comfortable with this framework, you can use it in Rails framework by using rspec rails gem .Testing and BDD is one of the most have skills for developer. You can save lots of time while developing the web applications. For developing APIs testing is one of the most have skill because we won’t have any view layer in those.

LEAVE A REPLY

Please enter your comment!
Please enter your name here