views:

441

answers:

1

Hi, I'm new to rails and I'm trying to test a controller with rspec. My first test is when the show action is invoked, it should lookup a Category by url.

The problem is when I add the stubbing code, I get the following error:

undefined method `find' for #

my test looks like this:

require 'spec_helper'

describe CategoriesController do
    describe "GET /category-name/" do
        before(:each) do
            @category = mock_model(Category)
            Category.stub!(:find).with(:first, :conditions => ["url = :url", {:url => "category-name"}]).and_return(@category)
        end

        it "should find the category by url" do
            controller.show
            Category.should_receive(:find).with(:first, :conditions => ["url = :url", {:url => "category-name"}]).and_return(@category)
        end
    end
end
+2  A: 

Your call to the request should be after any should_receive. It's a tense thing. So it kind of reads like this, "Category should receive something, when this happens". "This happens" refers to the request.

it "should find the category by url" do
  Category.should_receive(:find).with... 
  get "show", { your params, if you're sending some in }
end

Also, you want to go the way of a request vs calling the controller method itself, for this particular test at least.

So

post   "action_name"
get    "action_name"
update "action_name"
delete "action_name"

instead of

controller.action_name
nowk
ah, great, thanks. Now the stubbing works correctly but if i try using get "show" i get an error saying:No route matches {:action=>"show", :controller=>"categories"}but rake routes returns:root / {:controller=>"categories", :action=>"index"} /:url {:controller=>"categories", :action=>"show"}
Michael Baldry
nevermind, I've worked it out. I needed to pass :url to get :show that is why it didn't find my route. Thanks for your help
Michael Baldry