Created
November 7, 2012 08:25
-
-
Save xirukitepe/4030173 to your computer and use it in GitHub Desktop.
mocks and stubs example in rspec
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Mocks and stubs way | |
#The other option is to use mocks and stubs. Although there is a lot of information in the web about it, to help our discussion, I will #describe it very shortly. From my experience & research, I understand that the main difference between those two is the following: | |
#Stubbing a method is all about replacing the method with code that returns a specified result (or perhaps raises a specified exception). #Mocking a method is all about asserting that a method has been called (perhaps with particular parameters). | |
#As you can see, stubbing lets you define methods that are not currently implemented or we decided not to depend on. On the other hand, as we #mock objects we specify the behavior that we would expect on the mocked object, making our test more Behavior Driven Development. | |
#This is the recommended way of using Rspec as it defines the way the objects must collaborate to accomplish a certain task. | |
#Here we show how we implement the chat's example using mocks. | |
#spec/views/chat/show.html.erb_spec.rb | |
describe "/chats/show.html.erb" do | |
include ChatsHelper | |
before(:each) do | |
@chat = mock_model(Chat) | |
@chat.stub!(:name).and_return("MyString") | |
@chat.stub!(:id).and_return(1) | |
@chat.stub!(:to_param).and_return(1) | |
message_1 = mock_model(Message) | |
message_1.stub!(:data).and_return("Hello!") | |
message_1.stub!(:version).and_return(1) | |
message_2 = mock_model(Message) | |
message_2.stub!(:data).and_return("How are you?") | |
message_2.stub!(:version).and_return(2) | |
message_3 = mock_model(Message) | |
message_3.stub!(:data).and_return("Excellent!") | |
message_3.stub!(:version).and_return(3) | |
@messages = [message_1, message_2, message_3] | |
@chat.stub!(:messages).and_return(@messages) | |
@message.stub!(:data) | |
assigns[:chat] = @chat | |
render "/chats/show.html.erb" | |
end | |
it "should render attributes in paragraph" do | |
response.should have_text(/MyString/) | |
end | |
it "should render all messages for the chat" do | |
response.should have_tag("tr>td", "Hello!", 1) | |
response.should have_tag("tr>td", "How are you?", 1) | |
response.should have_tag("tr>td", "Excellent!", 1) | |
end | |
end | |
#As you can see, the idea behind mocks is to define some behavior that should be part of certain task, and it is very human readable as it #uses many features of Rspec mocks. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment