RSpec – Test Doubles ”; Previous Next In this chapter, we will discuss RSpec Doubles, also known as RSpec Mocks. A Double is an object which can “stand in” for another object. You’re probably wondering what that means exactly and why you’d need one. Let’s say you are building an application for a school and you have a class representing a classroom of students and another class for students, that is you have a Classroom class and a Student class. You need to write the code for one of the classes first, so let’s say that, start with the Classroom class − class ClassRoom def initialize(students) @students = students end def list_student_names @students.map(&:name).join(”,”) end end This is a simple class, it has one method list_student_names, which returns a comma delimited string of student names. Now, we want to create tests for this class but how do we do that if we haven’t created the Student class yet? We need a test Double. Also, if we have a “dummy” class that behaves like a Student object then our ClassRoom tests will not depend on the Student class. We call this test isolation. If our ClassRoom tests don’t rely on any other classes, then when a test fails, we can know immediately that there is a bug in our ClassRoom class and not some other class. Keep in mind that, in the real world, you may be building a class that needs to interact with another class written by someone else. This is where RSpec Doubles (mocks) become useful. Our list_student_names method calls the name method on each Student object in its @students member variable. Therefore, we need a Double which implements a name method. Here is the code for ClassRoom along with an RSpec Example (test), yet notice that there is no Student class defined − class ClassRoom def initialize(students) @students = students end def list_student_names @students.map(&:name).join(”,”) end end describe ClassRoom do it ”the list_student_names method should work correctly” do student1 = double(”student”) student2 = double(”student”) allow(student1).to receive(:name) { ”John Smith”} allow(student2).to receive(:name) { ”Jill Smith”} cr = ClassRoom.new [student1,student2] expect(cr.list_student_names).to eq(”John Smith,Jill Smith”) end end When the above code is executed, it will produce the following output. The elapsed time may be slightly different on your computer − . Finished in 0.01 seconds (files took 0.11201 seconds to load) 1 example, 0 failures As you can see, using a test double allows you to test your code even when it relies on a class that is undefined or unavailable. Also, this means that when there is a test failure, you can tell right away that it’s because of an issue in your class and not a class written by someone else. Print Page Previous Next Advertisements ”;
Category: Computer Programming
RSpec – Basic Syntax
RSpec – Basic Syntax ”; Previous Next Let’s take a closer look at the code of our HelloWorld example. First of all, in case it isn’t clear, we are testing the functionality of the HelloWorld class. This of course, is a very simple class that contains only one method say_hello(). Here is the RSpec code again − describe HelloWorld do context “When testing the HelloWorld class” do it “The say_hello method should return ”Hello World”” do hw = HelloWorld.new message = hw.say_hello expect(message).to eq “Hello World!” end end end The describe Keyword The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument. You also need to pass a block argument to describe, this will contain the individual tests, or as they are known in RSpec, the “Examples”. The block is just a Ruby block designated by the Ruby do/end keywords. The context Keyword The context keyword is similar to describe. It too can accept a class name and/or string argument. You should use a block with context as well. The idea of context is that it encloses tests of a certain type. For example, you can specify groups of Examples with different contexts like this − context “When passing bad parameters to the foobar() method” context “When passing valid parameters to the foobar() method” context “When testing corner cases with the foobar() method” The context keyword is not mandatory, but it helps to add more details about the examples that it contains. The it Keyword The word it is another RSpec keyword which is used to define an “Example”. An example is basically a test or a test case. Again, like describe and context, it accepts both class name and string arguments and should be used with a block argument, designated with do/end. In the case of it, it is customary to only pass a string and block argument. The string argument often uses the word “should” and is meant to describe what specific behavior should happen inside the it block. In other words, it describes that expected outcome is for the Example. Note the it block from our HelloWorld Example − it “The say_hello method should return ”Hello World”” do The string makes it clear what should happen when we call say hello on an instance of the HelloWorld class. This part of the RSpec philosophy, an Example is not just a test, it’s also a specification (a spec). In other words, an Example both documents and tests the expected behavior of your Ruby code. The expect Keyword The expect keyword is used to define an “Expectation” in RSpec. This is a verification step where we check, that a specific expected condition has been met. From our HelloWorld Example, we have − expect(message).to eql “Hello World!” The idea with expect statements is that they read like normal English. You can say this aloud as “Expect the variable message to equal the string ‘Hello World’”. The idea is that its descriptive and also easy to read, even for non-technical stakeholders such as project managers. The to keyword The to keyword is used as part of expect statements. Note that you can also use the not_to keyword to express the opposite, when you want the Expectation to be false. You can see that to is used with a dot, expect(message).to, because it actually just a regular Ruby method. In fact, all of the RSpec keywords are really just Ruby methods. The eql keyword The eql keyword is a special RSpec keyword called a Matcher. You use Matchers to specify what type of condition you are testing to be true (or false). In our HelloWorld expect statement, it is clear that eql means string equality. Note that, there are different types of equality operators in Ruby and consequently different corresponding Matchers in RSpec. We will explore the many different types of Matchers in a later section. Print Page Previous Next Advertisements ”;
RSpec – Writing Specs
RSpec – Writing Specs ”; Previous Next In this chapter, we will create a new Ruby class, save it in its own file and create a separate spec file to test this class. First, in our new class, it is called StringAnalyzer. It’s a simple class that, you guessed it, analyzes strings. Our class has only one method has_vowels? which as its names suggests, returns true if a string contains vowels and false if it doesn’t. Here’s the implementation for StringAnalyzer − class StringAnalyzer def has_vowels?(str) !!(str =~ /[aeio]+/i) end end If you followed the HelloWorld section, you created a folder called C:rspec_tutorialspec. Delete the hello_world.rb file if you have it and save the StringAnalyzer code above to a file called string_analyzer.rb in the C:rspec_tutorialspec folder. Here is the source for our spec file to test StringAnalyzer − require ”string_analyzer” describe StringAnalyzer do context “With valid input” do it “should detect when a string contains vowels” do sa = StringAnalyzer.new test_string = ”uuu” expect(sa.has_vowels? test_string).to be true end it “should detect when a string doesn”t contain vowels” do sa = StringAnalyzer.new test_string = ”bcdfg” expect(sa.has_vowels? test_string).to be false end end end Save this in the same spec directory, giving it the name string_analyzer_test.rb. In your cmd.exe window, cd to the C:rspec_tutorial folder and run this command: dir spec You should see the following − Directory of C:rspec_tutorialspec 09/13/2015 08:22 AM <DIR> . 09/13/2015 08:22 AM <DIR> .. 09/12/2015 11:44 PM 81 string_analyzer.rb 09/12/2015 11:46 PM 451 string_analyzer_test.rb Now we’re going to run our tests, run this command: rspec spec When you pass the name of a folder to rspec, it runs all of the spec files inside of the folder. You should see this result − No examples found. Finished in 0 seconds (files took 0.068 seconds to load) 0 examples, 0 failures The reason that this happened is that, by default, rspec only runs files whose names end in “_spec.rb”. Rename string_analyzer_test.rb to string_analyzer_spec.rb. You can do that easily by running this command − ren specstring_analyzer_test.rb string_analyzer_spec.rb Now, run rspec spec again, you should see output that looks like this − F. Failures: 1) StringAnalyzer With valid input should detect when a string contains vowels Failure/Error: expect(sa.has_vowels? test_string).to be true expected true got false # ./spec/string_analyzer_spec.rb:9:in `block (3 levels) in <top (required)>” Finished in 0.015 seconds (files took 0.12201 seconds to load) 2 examples, 1 failure Failed examples: rspec ./spec/string_analyzer_spec.rb:6 # StringAnalyzer With valid input should detect when a string contains vowels Do you see what just happened? Our spec failed because we have a bug in StringAnalyzer. The bug is simple to fix, open up string_analyzer.rb in a text editor and change this line: !!(str =~ /[aeio]+/i) to this: !!(str =~ /[aeiou]+/i) Now, save the changes you just made in string_analyizer.rb and run the rspec spec command again, you should now see output that looks like − .. Finished in 0.002 seconds (files took 0.11401 seconds to load) 2 examples, 0 failures Congratulations, the examples (tests) in your spec file are now passing. We fixed a bug in the regular expression which has vowels method but our tests are far from complete. It would make sense to add more examples that tests various types of input strings with the has vowels method. The following table shows some of the permutations that could be added in new Examples (it blocks) Input string Description Expected result with has_vowels? ‘aaa’, ‘eee’, ‘iii’, ‘o’ Only one vowel and no other letters. true ‘abcefg’ ‘At least one vowel and some consonants’ true ‘mnklp’ Only consonants. false ‘’ Empty string (no letters) false ‘abcde55345&??’ Vowels, consonants, numbers and punctuation characters. true ‘423432%%%^&’ Numbers and punctuation characters only. false ‘AEIOU’ Upper case vowels only. true ‘AeiOuuuA’ Upper case and lower vowels only. true ‘AbCdEfghI’ Upper and lower case vowels and consonants. true ‘BCDFG’ Upper case consonants only. false ‘ ‘ Whitespace characters only. false It is up to you to decide, which examples to add to your spec file. There are many conditions to test for, you need to determine what subset of conditions is most important and tests your code the best. The rspec command offers many different options, to see them all, type rspec -help. The following table lists the most popular options and describes what they do. Sr.No. Option/flag & Description 1 -I PATH Adds PATH to the load (require) path that rspec uses when looking for Ruby source files. 2 -r, –require PATH Adds a specific source file to be required in your spec. file(s). 3 –fail-fast With this option, rspec will stop running specs after the first Example fails. By default, rspec runs all specified spec files, no matter how many failures there are. 4 -f, –format FORMATTER This option allows you to specify different output formats. See the section on Formatters for more details about output formats. 5 -o, –out FILE This option directs rspec to write the test results to the output file FILE instead of to standard out. 6 -c, –color Enables color in rspec’s output. Successful Example results will display in green text, failures will print in red text. 7 -b, –backtrace Displays full error backtraces in rspec’s output. 8 -w, –warnings Displays Ruby warnings in rspec’s output. 9 -P, –pattern PATTERN Load and run spec files that match the pattern PATTERN. For example, if you pass -p “*.rb”, rspec will run all Ruby files, not just the ones that end in “_spec.rb”. 10 -e, –example STRING This option directs rspec to run all Examples that contain the text STRING in their descriptions. 11 -t, –tag TAG With this option, rspec will only run examples that contain the tag TAG. Note that TAG is specified as a Ruby symbol. See the section on RSpec Tags for more details. Print Page Previous Next Advertisements ”;
Prolog – Operators
Prolog – Operators ”; Previous Next In the following sections, we will see what are the different types of operators in Prolog. Types of the comparison operators and Arithmetic operators. We will also see how these are different from any other high level language operators, how they are syntactically different, and how they are different in their work. Also we will see some practical demonstration to understand the usage of different operators. Comparison Operators Comparison operators are used to compare two equations or states. Following are different comparison operators − Operator Meaning X > Y X is greater than Y X < Y X is less than Y X >= Y X is greater than or equal to Y X =< Y X is less than or equal to Y X =:= Y the X and Y values are equal X == Y the X and Y values are not equal You can see that the ‘=<’ operator, ‘=:=’ operator and ‘==’ operators are syntactically different from other languages. Let us see some practical demonstration to this. Example | ?- 1+2=:=2+1. yes | ?- 1+2=2+1. no | ?- 1+A=B+2. A = 2 B = 1 yes | ?- 5<10. yes | ?- 5>10. no | ?- 10==100. yes Here we can see 1+2=:=2+1 is returning true, but 1+2=2+1 is returning false. This is because, in the first case it is checking whether the value of 1 + 2 is same as 2 + 1 or not, and the other one is checking whether two patterns ‘1+2’ and ‘2+1’ are same or not. As they are not same, it returns no (false). In the case of 1+A=B+2, A and B are two variables, and they are automatically assigned to some values that will match the pattern. Arithmetic Operators in Prolog Arithmetic operators are used to perform arithmetic operations. There are few different types of arithmetic operators as follows − Operator Meaning + Addition – Subtraction * Multiplication / Division ** Power // Integer Division mod Modulus Let us see one practical code to understand the usage of these operators. Program calc :- X is 100 + 200,write(”100 + 200 is ”),write(X),nl, Y is 400 – 150,write(”400 – 150 is ”),write(Y),nl, Z is 10 * 300,write(”10 * 300 is ”),write(Z),nl, A is 100 / 30,write(”100 / 30 is ”),write(A),nl, B is 100 // 30,write(”100 // 30 is ”),write(B),nl, C is 100 ** 2,write(”100 ** 2 is ”),write(C),nl, D is 100 mod 30,write(”100 mod 30 is ”),write(D),nl. Note − The nl is used to create new line. Output | ?- change_directory(”D:/TP Prolog/Sample_Codes”). yes | ?- [op_arith]. compiling D:/TP Prolog/Sample_Codes/op_arith.pl for byte code… D:/TP Prolog/Sample_Codes/op_arith.pl compiled, 6 lines read – 2390 bytes written, 11 ms yes | ?- calc. 100 + 200 is 300 400 – 150 is 250 10 * 300 is 3000 100 / 30 is 3.3333333333333335 100 // 30 is 3 100 ** 2 is 10000.0 100 mod 30 is 10 yes | ?- Print Page Previous Next Advertisements ”;
Prolog – Lists
Prolog – Lists ”; Previous Next In this chapter, we will discuss one of the important concepts in Prolog, The Lists. It is a data structure that can be used in different cases for non-numeric programming. Lists are used to store the atoms as a collection. In the subsequent sections, we will discuss the following topics − Representation of lists in Prolog Basic operations on prolog such as Insert, delete, update, append. Repositioning operators such as permutation, combination, etc. Set operations like set union, set intersection, etc. Representation of Lists The list is a simple data structure that is widely used in non-numeric programming. List consists of any number of items, for example, red, green, blue, white, dark. It will be represented as, [red, green, blue, white, dark]. The list of elements will be enclosed with square brackets. A list can be either empty or non-empty. In the first case, the list is simply written as a Prolog atom, []. In the second case, the list consists of two things as given below − The first item, called the head of the list; The remaining part of the list, called the tail. Suppose we have a list like: [red, green, blue, white, dark]. Here the head is red and tail is [green, blue, white, dark]. So the tail is another list. Now, let us consider we have a list, L = [a, b, c]. If we write Tail = [b, c] then we can also write the list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts. So the following list representations are also valid − [a, b, c] = [x | [b, c] ] [a, b, c] = [a, b | [c] ] [a, b, c] = [a, b, c | [ ] ] For these properties we can define the list as − A data structure that is either empty or consists of two parts − a head and a tail. The tail itself has to be a list. Basic Operations on Lists Following table contains various operations on prolog lists − Operations Definition Membership Checking During this operation, we can verify whether a given element is member of specified list or not? Length Calculation With this operation, we can find the length of a list. Concatenation Concatenation is an operation which is used to join/add two lists. Delete Items This operation removes the specified element from a list. Append Items Append operation adds one list into another (as an item). Insert Items This operation inserts a given item into a list. Membership Operation During this operation, we can check whether a member X is present in list L or not? So how to check this? Well, we have to define one predicate to do so. Suppose the predicate name is list_member(X,L). The goal of this predicate is to check whether X is present in L or not. To design this predicate, we can follow these observations. X is a member of L if either − X is head of L, or X is a member of the tail of L Program list_member(X,[X|_]). list_member(X,[_|TAIL]) :- list_member(X,TAIL). Output | ?- [list_basics]. compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code… D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 1 lines read – 467 bytes written, 13 ms yes | ?- list_member(b,[a,b,c]). true ? yes | ?- list_member(b,[a,[b,c]]). no | ?- list_member([b,c],[a,[b,c]]). true ? yes | ?- list_member(d,[a,b,c]). no | ?- list_member(d,[a,b,c]). Length Calculation This is used to find the length of list L. We will define one predicate to do this task. Suppose the predicate name is list_length(L,N). This takes L and N as input argument. This will count the elements in a list L and instantiate N to their number. As was the case with our previous relations involving lists, it is useful to consider two cases − If list is empty, then length is 0. If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail. Program list_length([],0). list_length([_|TAIL],N) :- list_length(TAIL,N1), N is N1 + 1. Output | ?- [list_basics]. compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code… D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 4 lines read – 985 bytes written, 23 ms yes | ?- list_length([a,b,c,d,e,f,g,h,i,j],Len). Len = 10 yes | ?- list_length([],Len). Len = 0 yes | ?- list_length([[a,b],[c,d],[e,f]],Len). Len = 3 yes | ?- Concatenation Concatenation of two lists means adding the list items of the second list after the first one. So if two lists are [a,b,c] and [1,2], then the final list will be [a,b,c,1,2]. So to do this task we will create one predicate called list_concat(), that will take first list L1, second list L2, and the L3 as resultant list. There are two observations here. If the first list is empty, and second list is L, then the resultant list will be L. If the first list is not empty, then write this as [Head|Tail], concatenate Tail with L2 recursively, and store into new list in the form, [Head|New List]. Program list_concat([],L,L). list_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3). Output | ?- [list_basics]. compiling D:/TP Prolog/Sample_Codes/list_basics.pl for byte code… D:/TP Prolog/Sample_Codes/list_basics.pl compiled, 7 lines read – 1367 bytes written, 19 ms yes | ?- list_concat([1,2],[a,b,c],NewList). NewList = [1,2,a,b,c] yes | ?- list_concat([],[a,b,c],NewList). NewList = [a,b,c] yes | ?- list_concat([[1,2,3],[p,q,r]],[a,b,c],NewList). NewList = [[1,2,3],[p,q,r],a,b,c] yes | ?- Delete from List Suppose we have a list L and an element X, we have to delete X from L. So there are three cases − If X is the only element, then after deleting it, it will return empty list. If X is head of L, the resultant list will be the Tail part. If X is present
Prolog – Basic Programs
Prolog – Basic Programs ”; Previous Next In the following chapter, we are going to discuss basic prolog examples to − Find minimum maximum of two numbers Find the equivalent resistance of a resistive circuit Verify whether a line segment is horizontal, vertical or oblique Max and Min of two numbers Here we will see one Prolog program, that can find the minimum of two numbers and the maximum of two numbers. First, we will create two predicates, find_max(X,Y,Max). This takes X and Y values, and stores the maximum value into the Max. Similarly find_min(X,Y,Min) takes X and Y values, and store the minimum value into the Min variable. Program find_max(X, Y, X) :- X >= Y, !. find_max(X, Y, Y) :- X < Y. find_min(X, Y, X) :- X =< Y, !. find_min(X, Y, Y) :- X > Y. Output | ?- find_max(100,200,Max). Max = 200 yes | ?- find_max(40,10,Max). Max = 40 yes | ?- find_min(40,10,Min). Min = 10 yes | ?- find_min(100,200,Min). Min = 100 yes | ?- Resistance and Resistive Circuits In this section, we will see how to write a prolog program that will help us find the equivalent resistance of a resistive circuit. Let us consider the following circuit to understand this concept − We have to find the equivalent resistance of this network. At first, we will try to get the result by hand, then try to see whether the result is matching with the prolog output or not. We know that there are two rules − If R1 and R2 are in Series, then equivalent resistor Re = R1 + R2. If R1 and R2 are in Parallel, then equivalent resistor Re = (R1 * R2)/(R1 + R2). Here 10 Ohm and 40 Ohm resistors are in parallel, then that is in series with 12 Ohm, and the equivalent resistor of the lower half is parallel with 30 Ohm. So let’s try to calculate the equivalent resistance. R3 = (10 * 40)/(10 + 40) = 400/50 = 8 Ohm R4 = R3 + 12 = 8 + 12 = 20 Ohm R5 = (20 * 30)/(20 + 30) = 12 Ohm Program series(R1,R2,Re) :- Re is R1 + R2. parallel(R1,R2,Re) :- Re is ((R1 * R2) / (R1 + R2)). Output | ?- [resistance]. compiling D:/TP Prolog/Sample_Codes/resistance.pl for byte code… D:/TP Prolog/Sample_Codes/resistance.pl compiled, 1 lines read – 804 bytes written, 14 ms yes | ?- parallel(10,40,R3). R3 = 8.0 yes | ?- series(8,12,R4). R4 = 20 yes | ?- parallel(20,30,R5). R5 = 12.0 yes | ?- parallel(10,40,R3),series(R3,12,R4),parallel(R4,30,R5). R3 = 8.0 R4 = 20.0 R5 = 12.0 yes | ?- Horizontal and Vertical Line Segments There are three types of line segments, horizontal, vertical or oblique. This example verifies whether a line segment is horizontal, vertical or oblique. From this diagram we can understand that − For Horizontal lines, the y coordinate values of two endpoints are same. For Vertical lines, the x coordinate values of two endpoints are same. For Oblique lines, the (x,y) coordinates of two endpoints are different. Now let us see how to write a program to check this. Program vertical(seg(point(X,_),point(X,_))). horizontal(seg(point(_,Y),point(_,Y))). oblique(seg(point(X1,Y1),point(X2,Y2))) :-X1 == X2, Y1 == Y2. Output | ?- [line_seg]. compiling D:/TP Prolog/Sample_Codes/line_seg.pl for byte code… D:/TP Prolog/Sample_Codes/line_seg.pl compiled, 6 lines read – 1276 bytes written, 26 ms yes | ?- vertical(seg(point(10,20), point(10,30))). yes | ?- vertical(seg(point(10,20), point(15,30))). no | ?- oblique(seg(point(10,20), point(15,30))). yes | ?- oblique(seg(point(10,20), point(15,20))). no | ?- horizontal(seg(point(10,20), point(15,20))). yes | ?- Print Page Previous Next Advertisements ”;
Recursion and Structures
Prolog – Recursion and Structures ”; Previous Next This chapter covers recursion and structures. Recursion Recursion is a technique in which one predicate uses itself (may be with some other predicates) to find the truth value. Let us understand this definition with the help of an example − is_digesting(X,Y) :- just_ate(X,Y). is_digesting(X,Y) :-just_ate(X,Z),is_digesting(Z,Y). So this predicate is recursive in nature. Suppose we say that just_ate(deer, grass), it means is_digesting(deer, grass) is true. Now if we say is_digesting(tiger, grass), this will be true if is_digesting(tiger, grass) :- just_ate(tiger, deer), is_digesting(deer, grass), then the statement is_digesting(tiger, grass) is also true. There may be some other examples also, so let us see one family example. So if we want to express the predecessor logic, that can be expressed using the following diagram − So we can understand the predecessor relationship is recursive. We can express this relationship using the following syntax − predecessor(X, Z) :- parent(X, Z). predecessor(X, Z) :- parent(X, Y),predecessor(Y, Z). Structures Structures are Data Objects that contain multiple components. For example, the date can be viewed as a structure with three components — day, month and year. Then the date 9th April, 2020 can be written as: date(9, apr, 2020). Note − Structure can in turn have another structure as a component in it. So we can see views as tree structure and Prolog Functors. Now let us see one example of structures in Prolog. We will define a structure of points, Segments and Triangle as structures. To represent a point, a line segment and a triangle using structure in Prolog, we can consider following statements − p1 − point(1, 1) p2 − point(2,3) S − seg( Pl, P2): seg( point(1,1), point(2,3)) T − triangle( point(4,Z), point(6,4), point(7,1) ) Note − Structures can be naturally pictured as trees. Prolog can be viewed as a language for processing trees. Matching in Prolog Matching is used to check whether two given terms are same (identical) or the variables in both terms can have the same objects after being instantiated. Let us see one example. Suppose date structure is defined as date(D,M,2020) = date(D1,apr, Y1), this indicates that D = D1, M = feb and Y1 = 2020. Following rules are to be used to check whether two terms S and T match − If S and T are constants, S=T if both are same objects. If S is a variable and T is anything, T=S. If T is variable and S is anything, S=T. If S and T are structures, S=T if − S and T have same functor. All their corresponding arguments components have to match. Binary Trees Following is the structure of binary tree using recursive structures − The definition of the structure is as follows − node(2, node(1,nil,nil), node(6, node(4,node(3,nil,nil), node(5,nil,nil)), node(7,nil,nil)) Each node has three fields, data and two nodes. One node with no child (leaf node) structure is written as node(value, nil, nil), node with only one left child is written as node(value, left_node, nil), node with only one right child is written as node(value, nil; right_node), and node with both child has node(value, left_node, right_node). Print Page Previous Next Advertisements ”;
RSpec – Introduction
RSpec – Introduction ”; Previous Next RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool. What this means is that, tests written in RSpec focus on the “behavior” of an application being tested. RSpec does not put emphasis on, how the application works but instead on how it behaves, in other words, what the application actually does. RSpec Environment First of all, you will need to install Ruby on your computer. However, if you haven’t already done earlier, then you can download and install Ruby from the main Ruby website − Ruby. If you are installing Ruby on Windows, you should have the Ruby installer for Windows here at − http://www.rubyinstaller.org For this tutorial, you will only need text editor, such as Notepad and a command line console. The examples here will use cmd.exe on Windows. To run cmd.exe, simply click on the Start menu and type “cmd.exe”, then hit the Return key. At the command prompt in your cmd.exe window, type the following command to see what version of Ruby you are using − ruby -v You should see the below output that looks similar to this − ruby 2.2.3p173 (2015-08-18 revision 51636) [x64-mingw32] The examples in this tutorial will use Ruby 2.2.3 but any version of Ruby higher than 2.0.0 will suffice. Next, we need to install the RSpec gem for your Ruby installation. A gem is a Ruby library which you can use in your own code. In order to install a gem, you need to use the gem command. Let’s install the Rspec gem now. Go back to your cmd.exe Window and type the following − gem install rspec You should have a list of dependent gems that were installed, these are gems that the rspec gem needs to function correctly. At the end of the output, you should see something that looks like this − Done installing documentation for diff-lcs, rspec-support, rspec-mocks, rspec-expectations, rspec-core, rspec after 22 seconds 6 gems installed Do not worry, if your output does not look exactly the same. Also, if you are using a Mac or Linux computer, you may need to either run gem install rspec command using sudo or use a tool like HomeBrew or RVM to install the rspec gem. Hello World To get started, let’s create a directory (folder) to store our RSpec files. In your cmd.exe window, type the following − cd Then type − mkdir rspec_tutorial And finally, type − cd rspec_tutorial From here, we’re going to create another directory named spec, do that by typing − mkdir spec We are going to store our RSpec files in this folder. RSpec files are known as “specs”. If this seems confusing to you, you can think of a spec file as a test file. RSpec uses the term “spec” which is a short form for “specification”. Since, RSpec is a BDD test tool, the goal is to focus on what the application does and whether or not it follows a specification. In behavior driven development, the specification is often described in terms of a “User Story”. RSpec is designed to make it clear whether the target code is behaving correctly, in other words following the specification. Let’s return to our Hello World code. Open a text editor and add the following code − class HelloWorld def say_hello “Hello World!” end end describe HelloWorld do context “When testing the HelloWorld class” do it “should say ”Hello World” when we call the say_hello method” do hw = HelloWorld.new message = hw.say_hello expect(message).to eq “Hello World!” end end end Next, save this to a file named hello_world_spec.rb in the spec folder that you created above. Now back in your cmd.exe window, run this command − rspec spec spechello_world_spec.rb When the command completes, you should see output that looks like this − Finished in 0.002 seconds (files took 0.11101 seconds to load) 1 example, 0 failures Congratulations, you just created and ran your first RSpec unit test! In the next section, we will continue to discuss the syntax of RSpec files. Print Page Previous Next Advertisements ”;
RSpec – Home
RSpec Tutorial PDF Version Quick Guide Resources Job Search Discussion RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool. What this means is that, tests written in RSpec focus on the “behavior” of an application being tested. RSpec does not put emphasis on, how the application works but instead on how it behaves, in other words, what the application actually does. This tutorial will show you, how to use RSpec to test your code when building applications with Ruby. Audience This tutorial is for beginners who want to learn how to write better code in Ruby. After finishing this tutorial, you will be able to incorporate RSpec tests into your daily coding practices. Prerequisites In order to benefit from reading this tutorial, you should have some experience with programming, specifically with Ruby. Print Page Previous Next Advertisements ”;
Prolog – Backtracking
Prolog – Backtracking ”; Previous Next In this chapter, we will discuss the backtracking in Prolog. Backtracking is a procedure, in which prolog searches the truth value of different predicates by checking whether they are correct or not. The backtracking term is quite common in algorithm designing, and in different programming environments. In Prolog, until it reaches proper destination, it tries to backtrack. When the destination is found, it stops. Let us see how backtracking takes place using one tree like structure − Suppose A to G are some rules and facts. We start from A and want to reach G. The proper path will be A-C-G, but at first, it will go from A to B, then B to D. When it finds that D is not the destination, it backtracks to B, then go to E, and backtracks again to B, as there is no other child of B, then it backtracks to A, thus it searches for G, and finally found G in the path A-C-G. (Dashed lines are indicating the backtracking.) So when it finds G, it stops. How Backtracking works? Now we know, what is the backtracking in Prolog. Let us see one example, Note − While we are running some prolog code, during backtracking there may be multiple answers, we can press semicolon (;) to get next answers one by one, that helps to backtrack. Otherwise when we get one result, it will stop. Now, consider a situation, where two people X and Y can pay each other, but the condition is that a boy can pay to a girl, so X will be a boy, and Y will be a girl. So for these we have defined some facts and rules − Knowledge Base boy(tom). boy(bob). girl(alice). girl(lili). pay(X,Y) :- boy(X), girl(Y). Following is the illustration of the above scenario − As X will be a boy, so there are two choices, and for each boy there are two choices alice and lili. Now let us see the output, how backtracking is working. Output | ?- [backtrack]. compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code… D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 5 lines read – 703 bytes written, 22 ms yes | ?- pay(X,Y). X = tom Y = alice ? (15 ms) yes | ?- pay(X,Y). X = tom Y = alice ? ; X = tom Y = lili ? ; X = bob Y = alice ? ; X = bob Y = lili yes | ?- trace. The debugger will first creep — showing everything (trace) (16 ms) yes {trace} | ?- pay(X,Y). 1 1 Call: pay(_23,_24) ? 2 2 Call: boy(_23) ? 2 2 Exit: boy(tom) ? 3 2 Call: girl(_24) ? 3 2 Exit: girl(alice) ? 1 1 Exit: pay(tom,alice) ? X = tom Y = alice ? ; 1 1 Redo: pay(tom,alice) ? 3 2 Redo: girl(alice) ? 3 2 Exit: girl(lili) ? 1 1 Exit: pay(tom,lili) ? X = tom Y = lili ? ; 1 1 Redo: pay(tom,lili) ? 2 2 Redo: boy(tom) ? 2 2 Exit: boy(bob) ? 3 2 Call: girl(_24) ? 3 2 Exit: girl(alice) ? 1 1 Exit: pay(bob,alice) ? X = bob Y = alice ? ; 1 1 Redo: pay(bob,alice) ? 3 2 Redo: girl(alice) ? 3 2 Exit: girl(lili) ? 1 1 Exit: pay(bob,lili) ? X = bob Y = lili yes {trace} | ?- Preventing Backtracking So far we have seen some concepts of backtracking. Now let us see some drawbacks of backtracking. Sometimes we write the same predicates more than once when our program demands, for example to write recursive rules or to make some decision making systems. In such cases uncontrolled backtracking may cause inefficiency in a program. To resolve this, we will use the Cut in Prolog. Suppose we have some rules as follows − Double step function Rule 1 &minnus; if X < 3 then Y = 0 Rule 2 &minnus; if 3 <= X and X < 6 then Y = 2 Rule 3 &minnus; if 6 <= X then Y = 4 In Prolog syntax we can write, f(X,0) :- X < 3. % Rule 1 f(X,2) :- 3 =< X, X < 6. % Rule 2 f(X,4) :- 6 =< X. % Rule 3 Now if we ask for a question as f (1,Y), 2 The first goal f(1,Y) instantiated Y to 0. The second goal becomes 2 < 0 which fails. Prolog tries through backtracking two unfruitful alternatives (Rule 2 and Rule 3). If we see closer, we can observe that − The three rules are mutually exclusive and one of them at most will succeed. As soon as one of them succeeds there is no point in trying to use the others as they are bound to fail. So we can use cut to resolve this. The cut can be expressed using Exclamation symbol. The prolog syntax is as follows − f (X,0) :- X < 3, !. % Rule 1 f (X,2) :- 3 =< X, X < 6, !. % Rule 2 f (X,4) :- 6 =< X. % Rule 3 Now if we use the same question, ?- f (1,Y), 2 < Y. Prolog choose rule 1 since 1 < 3 and fails the goal 2 < Y fails. Prolog will try to backtrack, but not beyond the point marked ! In the program, rule 2 and rule 3 will not be generated. Let us see this in below execution − Program f(X,0) :- X < 3. % Rule 1 f(X,2) :- 3 =< X, X < 6. % Rule 2 f(X,4) :- 6 =< X. % Rule 3 Output | ?- [backtrack]. compiling D:/TP Prolog/Sample_Codes/backtrack.pl for byte code… D:/TP Prolog/Sample_Codes/backtrack.pl compiled, 10 lines read – 1224 bytes written, 17 ms yes | ?- f(1,Y), 2<Y. no | ?- trace . The debugger will first creep — showing everything (trace) yes {trace} | ?- f(1,Y), 2<Y. 1 1 Call: f(1,_23) ? 2 2 Call: