【问题标题】:Testing rails controller with rspec使用 rspec 测试 rails 控制器
【发布时间】:2010-02-28 22:40:26
【问题描述】:

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

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

##的未定义方法`find'

我的测试如下所示:

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

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    您对请求的调用应在任何should_receive 之后。这是一件很紧张的事情。所以它有点像这样,“当发生这种情况时,类别应该收到一些东西”。 “发生这种情况”是指请求。

    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" 我会收到一条错误消息:没有路由匹配 {:action=>"show", :controller=>"categories"} 但 rake 路由返回:root / {:controller =>"categories", :action=>"index"} /:url {:controller=>"categories", :action=>"show"}
    • 没关系,我已经解决了。我需要通过 :url 来获取 :show 这就是它找不到我的路线的原因。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多