使用rspec测试rails控制器

4

我是rails的新手,正在尝试使用rspec测试控制器。我的第一个测试是在调用show操作时,它应该通过url查找类别。

问题是当我添加桩代码时,我会收到以下错误:

undefined method `find' for #

我的测试看起来像这样:

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
1个回答

10

在任何should_receive之后,您对请求的调用应该完成。这是一种时态问题。所以它读起来有点像这样,“当this happens”时,类别应该接收到某些东西。 "This happens" 指的是请求。

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

此外,对于至少在这个测试中,您希望采用请求方式而不是直接调用控制器方法的方式。

因此

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

取代

controller.action_name

啊,太好了,谢谢。现在存根功能正常工作了,但是如果我尝试使用get“show”,就会出现错误,说:No route matches {:action=>"show", :controller=>"categories"}但rake routes返回: root / {:controller =>“categories”,:action =>“index”} /:url {:controller =>“categories”,:action =>“show”} - Michael Baldry
没事了,我已经解决了。我需要传递:url来获取:show,这就是为什么它找不到我的路由。感谢你的帮助。 - Michael Baldry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接