Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing rails controller with rspec

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
like image 815
Michael Baldry Avatar asked Dec 30 '22 00:12

Michael Baldry


1 Answers

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
like image 86
nowk Avatar answered Jan 12 '23 00:01

nowk