I have dabbled with RSpec with the Beta books but am only now getting my
teeth in to it. Because of this and because I have no one to ask/bounce
ideas off, I am asking for a kind soul to look at what I’ve done for my
first example. Am I on the right track with the way I’m thinking?
My first attempt at testing my real live thing was the following
(comments
included to help)
describe “GET edit” do
context “the product cutoff time has passed” do
it “prevents editing of the product” do
## ProductType object must be received on an edit
ProductType.should_receive(:find).with(“1”).and_return(ProductType)
ProductType.should_receive(:products).and_return(Product)
Product.stub(:find).with("1").and_return(Product)
## this is the thing I really want to test
Product.should_receive(:product_cutoff_passed?).and_return(true)
## before filters
controller.stub(:authorise_is_admin).and_return(true)
controller.stub(:require_user).and_return(user)
get :edit, :product_type_id => 1, :id => 1
flash[:notice].should == "The product is closed for editing"
response.should redirect_to(products_path)
end
end
end
I got the above example passing and then went about refactoring it and
this
is what I have now
def require_user
controller.stub(:require_user).and_return(User)
end
def authorise_is_admin
controller.stub(:authorise_is_admin).and_return(true)
end
describe ProductsController do
this is required for all actions in this controller
before(:each) do
require_user
end
let(:product_type) { mock_model(ProductType).as_null_object }
let(:product) { mock_model(Product).as_null_object }
describe “GET edit” do
## this is required for this action
before(:each) do
authorise_is_admin
end
## this now has its own test as it is fundamental to the action
it "creates a ProductType object" do
## message expectation
ProductType.should_receive(:find).with("1").and_return(product_type)45
get :edit, :product_type_id => 1, :id => 1
end
## the message expectations in my first example are now stubs in
this
example
## as they are not the main focus of this test
context “the product cutoff time has passed” do
it “prevents editing of the product” do
ProductType.stub(:find).with(“1”).and_return(product_type)
## would like to use stub_chain but one of the stubs receives
arguments
product_type.stub(:products).and_return(product)
product.stub(:find).with(“1”).and_return(product)
## message expectation
product.should_receive(:product_cutoff_passed?).and_return(true)
get :edit, :product_type_id => 1, :id => 1
flash[:notice].should == "The product is closed for editing"
response.should redirect_to(products_path)
end
end
end
end
I hope you don;t mind if I do this as I will need your feedback to get
me in
the right way of thinking.
Thank you
-ants