Jump to content

User:Aagrawa6/sandbox

From Wikipedia, the free encyclopedia

An expectation is the most expected outcome of an event in case of uncertainty. In Ruby, there are various packages such as RSpec [1], Minitest[2], Mocha[3] etc. that lets the programmer to express expected outcomes on an object. These packages have grown their popularity by keeping things simple.

Introduction

[edit]

In Ruby, expectations are used to provide useful messages related to success, failure of the testcase etc., but if any more specific information is required, one can also define customized messages. RSpec package ships with a number of "built-in matchers[4]". These modules can be used to define positive and negative expectations on an object with expect(..).to and expect(..).not_to respectively. With Minitest, four types of expectations can be defined: unary expectations[5], binary expectations[5], reverse expectations[5] and block/proc expectations[5]. Mocha defines a traditional mock object. Calling a method on this object, it searches through its expectations from the newest expectation to the oldest expectation to find the one that matches the invocation. An expects(:bar).once expectation only matches once and is ignored on future calls while an expects(:bar).at_least_once expectation is matched upon every invocation.

RSpec::Expectations

[edit]

RSpec[6] is a Behavior Driven Development (BDD[7]) testing framework. RSpec::Expectations lets the programmer specify the expected outcome of an object in a test case.

Usage Examples

[edit]
class Greet
  def greet
    "Good Morning!"
  end
end

describe Greet do
  context "When testing greet method of Greet" do
    it "should return 'Good Morning!'" do
      good_morning = Greet.new
      expect(good_morning.greet).to eq("Good Morning!")
    end
  end
end

RSpec::Expectation has many methods which helps in verifying the returned result. The expect statement takes the argument to be tested and makes the validation based on the qualifiers provided as an argument. The to method is used with expect statement. As the name indicates, to method tests the actual argument against expected argument based on matcher's provided as an argument. In the above example, expect statement uses special RSpec keyword eq matcher. This matcher takes the expected value and passes unit test if actual value is same as expected value. Example test case passes only if the returned value from the actual method call good_morning.greet() is 'Good Morning!', otherwise test fails. In case of failure RSpec throws an error and indicates expected and observed values do not match. The programmer can also use not_to RSpec method for exact opposite matching. expect method was introducued in RSpec version 2.11. Before that should and should_not syntax were used. Latest RSpec versions support both expect and should syntax. But expect is recommended over should[8].

good_morning.greet().should eq("Good Morning!")
good_morning.greet().should_not eq("Good Night")

There are several built in matchers in RSpec which can be used with expect()..to or expect()..not_to to define the expectations on an object[9].

Built in matchers

[edit]
Matchers Description
eq, eql Evaluates to true if actual and expected object values are same
be, equal Evaluates to true if actual and expected objects refer to the same object
>, >=, <, <= Used to check whether actual value >, >=, <, <= to the expected value
be_empty Used to check whether the collection is empty
match Used to match the actual values using regular expression[10]
be_instance_of Used to check if the actual object belongs to the expected objects class
respond_to Tests if the actual object responds to the specified method
be_between(minimum_value,

maximum_value).inclusive

Tests if the actual value is between [minimum_value, maximum_value]
be_between(minimum_value,

maximum_value).exclusive

Tests if the actual value is between (minimum_value, maximum_value)
be true Tests if actual == true
be false Tests if actual == false

Mocha::Expectations

[edit]

Mocha is a Ruby library for mocking and stubbing. It provides a readable, unified and simple syntax for partial as well as full mocking. It is also supported by many other frameworks. A stub is a type of expectation of zero or more invocations. These are defined to make the intent of the test more explicit. Mocha defines a traditional mock object. The mock object searches through its expectations from newest to oldest to find one that matches the invocation.

Instance Methods Available

[edit]

All methods defined on Mock#expects, Mock#stubs, ObjectMethods#expects and ObjectMethods#stubs returns an Expectation. Various Instance methods available[11] are:

  1. (Expectation) at_least(minimum_number_of_times)
  2. (Expectation) at_least_once
  3. (Expectation) at_most(maximum_number_of_times)
  4. (Expectation) at_most_once
  5. (Expectation) in_sequence(*sequences)
  6. (Expectation) multiple_yields(*parameter_groups)
  7. (Expectation) never
  8. (Expectation) once
  9. (Expectation) raises(exception = RuntimeError, message = nil)
  10. (Expectation) returns(*values)
  11. (Expectation) then(*parameters)
  12. (Expectation) throws(tag, object = nil)
  13. (Expectation) times(range)
  14. (Expectation) twice
  15. (Expectation) when(state_predicate)
  16. (Expectation) with(*expected_parameters) {|actual_parameters| ... }
  17. (Expectation) yields(*parameters)

A Basic Example

[edit]
- (Expectation) at_least_once
object = mock()
object.expects(:expected_method).at_least_once
object.expected_method
# => verify succeeds

object = mock()
object.expects(:expected_method).at_least_once
# => verify fails

- (Expectation) at_most_once
object = mock()
object.expects(:expected_method).at_most_once
object.expected_method
# => verify succeeds

object = mock()
object.expects(:expected_method).at_most_once
2.times { object.expected_method } # => unexpected invocation

MiniTest::Expectations

[edit]

MiniTest is a testing framework which provides a complete set of testing utilities including mocking[12], benchmarking and Behaviour Driven Development. From Ruby 1.9, it's added as part of Ruby's standard library[13]. MiniTest provides expectation syntax which is similar to Rspec's Expectation syntax.

Usage Example

[edit]
require 'minitest/autorun'

class GoodMorning
  def greet
    "Good Morning!"
  end
end

describe GoodMorning do
    it "greet() should return 'Good Morning!'" do
      good_morning = GoodMorning.new
      good_morning.greet.must_equal "Good Morning!"
    end
end

Example shown above is almost similar to the example given in RSpec::Expectations section. Instead of expect().to ..eq() syntax, MiniTest uses must_equal.

But both the frameworks tests the value of actual and expected objects for equality. MiniTest::Expectations provides several inbuilt methods[14].

Built in methods

[edit]
Expectation methods Description
must_equal Evaluates to true if actual and expected object values are same
must_be(operator, expected) Takes operators like :<, :>= etc and returns true if (actual operator expected)

returns true

must_be_empty Tests whether the object is empty
must_be_kind_of(class) Test fails unless invoking object is of type class passed as an argument or it's super type
must_be_nil Test passes only if the object is nill
must_match Used to compare object values using regular expression
must_respond_to(message) Used to test if the method is present in the class

Above built in methods are positive expectations. MiniTest also provides built in negative expectation methods. In most of the cases we just need to replace 'must' with 'wont'. For example, wont_be, wont_be_empty, wont_match etc.

Videos

[edit]
  1. Stubbing and Mocking in RSpec
  2. Stubbing and Mocking with RSpec - The codeship
  3. RSpec - Should and Expect
  4. Understanding Mock Objects
  5. Getting Started with Minitest Rails

Further Reading

[edit]
  1. Customize minitest assertions and expectations
  2. Introduction to Mocha expectations
  3. Class Mocha: Mock, Stub, Instance methods
  4. RSpec: Built-in Matchers
  5. RSpec Expectations: 2.14

References

[edit]
  1. ^ "RSpec Expectations 3.5 - RSpec Expectations - RSpec - Relish". relishapp.com. Retrieved 2016-09-11.
  2. ^ "Module: MiniTest::Expectations (Ruby 2.1.0)". ruby-doc.org. Retrieved 2016-09-11.
  3. ^ "Class: Mocha::Expectation — Documentation for floehopper/mocha (master)". www.rubydoc.info. Retrieved 2016-09-11.
  4. ^ "Built in matchers - RSpec Expectations - RSpec - Relish". relishapp.com. Retrieved 2016-09-11.
  5. ^ a b c d Kottom, Chris. "Customize Minitest Assertions and Expectations". chriskottom.com. Retrieved 2016-09-11.
  6. ^ "About RSpec". rspec.info. Retrieved 2016-09-11.
  7. ^ "Behavior-driven development". Wikipedia, the free encyclopedia. 2016-09-03.
  8. ^ "RSpec's New Expectation Syntax". rspec.info. Retrieved 2016-09-11.
  9. ^ "Built in matchers - RSpec Expectations - RSpec - Relish". www.relishapp.com. Retrieved 2016-09-11.
  10. ^ "Class: Regexp (Ruby 2.2.0)". ruby-doc.org. Retrieved 2016-09-11.
  11. ^ "Class: Mocha::Expectation — Mocha 1.1.0". gofreerange.com. Retrieved 2016-09-11.
  12. ^ "Mock object". Wikipedia, the free encyclopedia. 2016-08-22.
  13. ^ "Getting Started with Minitest". semaphoreci.com. Retrieved 2016-09-12.
  14. ^ "Module: MiniTest::Expectations (Ruby 2.1.0)". ruby-doc.org. Retrieved 2016-09-11.