开发者

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 =>开发者_如何学Python; "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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜