RSpec
RSpec is a computer domain-specific language testing tool written in the programming language Ruby to test Ruby code. It is a behavior-driven development framework which is extensively used in production applications. The basic idea behind this concept is that of test-driven development where the tests are written first and the development is based on writing just enough code that will fulfill those tests followed by refactoring. It contains its own that is fully integrated into the framework based upon . The simplicity in the RSpec syntax makes it one of the popular testing tools for Ruby applications. The RSpec tool can be used by installing the
rspec gem which consists of three other gems, namely rspec-core, rspec-expectation and rspec-mock.History
RSpec was started as an experiment by Steven Baker in 2005 along with his team members Dave Astels, Aslak Hellesøy and David Chelimsky. Chelimsky was responsible for developing the RSpec-Rails which facilitated the integration with Ruby on Rails. The initial release i.e. RSpec 1.0 came out in May 2007 which contained many prime features of RSpec which are being included in the latest releases too. However, due to some technical issues such as testing speed, it was discontinued later. The third version of RSpec i.e. the RSpec 3 was released in July 2014 which had many new features like verify doubles, composable matchers and many more.Usage
Describing the behavior of objects
As mentioned above, RSpec provides a domain-specific language to describe the behavior of objects. The keywords used in RSpec are similar to the ones used in other languages and/or TDD frameworks. For example, if the keywords used in Test::Unit are considered, they can be mapped to the RSpec keywords as follows:- Assertion becomes expectation
- Test method becomes Example code
- Test case becomes Example group
describe User, "with no account balance"
=> User with no account balance
describe User do
context "has no account balance" do
....
end
end
describe User do
context "has no account balance" do
it "is not allowed to sanction a housing loan" do
puts "The loan cannot be sanctioned due to no balance in the account."
end
end
end
RSpec::Expectations
In RSpec, an expectation is a statement expressing the state that something is expected to be in, at a particular point in the execution of a code example. RSpec uses a simple framework and keywords like should and should_not to express expectations. It supports matchers, that is objects that try to match an expected outcome, for common operations as well as uncommon expressions. For example, if the expected outcome of a result is say numeric value 5, a RSpec expectation that uses the matcher equal for the same would be written as follows:result.should equal