【问题标题】:RSpec: Expectation on model's not working while testing controllerRSpec:在测试控制器时对模型不工作的期望
【发布时间】:2010-04-29 15:25:14
【问题描述】:

我正在尝试编写功能测试。我的测试如下:

describe PostsController do
  it "should create a Post" do
    Post.should_receive(:new).once
    post :create, { :post => { :caption => "ThePost", :category => "MyCategory" } }
  end
end

我的 PostsController(实际上是它的一部分)如下所示:

PostController < ActiveRecord::Base

  def create
    @post = Post.new(params[:post])
  end

end

运行测试我总是收到失败,这表明 Post 类期望 :new 但从未得到它。不过,实际的帖子已创建。

我是 RSpec 的新手。我错过了什么吗?

【问题讨论】:

    标签: ruby-on-rails testing rspec expectations


    【解决方案1】:

    EDIT - 扔掉以前的垃圾

    这应该做你想做的事

    require File.dirname(__FILE__) + '/../spec_helper'
    
    describe PostsController do
      it "should create a Post" do
        attributes = {"Category" => "MyCategory", "caption" => "ThePost"}
        Post.stub!(:new).and_return(@post = mock_model(Post, :save => false))
        Post.should_receive(:new).with( attributes ).and_return @post
        post :create, { :post => attributes }
      end
    end
    

    这假设您使用的是 rspecs 自己的模拟库并且您已安装 rspec_rails gem。

    【讨论】:

      【解决方案2】:

      您可以使用 Rspec-rails 的 controller 方法来测试控制器上的消息预期,如 here 所述。因此,测试您的 create 操作的一种方法如下:

      describe PostsController do
        it "should create a Post" do
          controller.should_receive(:create).once
          post :create, { :post => { :caption => "ThePost", :category => "MyCategory" } }
        end
      end
      

      编辑(提出论点)

      您可能需要考虑编写一个依赖于create 操作实现的测试是否是个好主意。如果您要测试的不是控制器的适当职责,那么您将面临重构时破坏测试的风险,并且在实现更改时不得不返回并重写测试。

      create 操作的工作是创建一些东西——所以测试一下:

      Post.count.should == 1

      然后您就知道是否创建了一个帖子,而不取决于它是如何创建的

      编辑#2(嗯...)

      我从您最初的问题中看到,您已经知道正在创建帖子。我仍然认为您应该测试行为而不是实现,并且在控制器测试中检查模型是否接收到消息并不是一件好事。也许您正在做的是调试,而不是测试?

      【讨论】:

      • 谢谢,但这不是我想要完成的事情。我想要做的是检查模型类是否收到了某个消息(例如:find、:create 等)
      猜你喜欢
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多