Ruby on rails RSpec:对模型的期望';测试控制器时,它不工作

Ruby on rails RSpec:对模型的期望';测试控制器时,它不工作,ruby-on-rails,testing,rspec,expectations,Ruby On Rails,Testing,Rspec,Expectations,我想写一个功能测试。我的测试如下所示: describe PostsController do it "should create a Post" do Post.should_receive(:new).once post :create, { :post => { :caption => "ThePost", :category => "MyCategory" } } end end PostController < ActiveRecord

我想写一个功能测试。我的测试如下所示:

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

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

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

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

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

end
PostController
运行测试时,我总是收到一个失败消息,这表示后课堂期望:新的,但从未得到它。尽管如此,实际的帖子还是被创建了


我是RSpec的新手。我遗漏了什么吗?

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

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

<>你可能想考虑写一个测试是否是一个好主意,这取决于<代码>创建< /COD>动作。如果您正在测试除控制器的适当职责之外的任何内容,那么在重构时您将面临中断测试的风险,并且在实现更改时必须返回并重写测试

create操作的任务是创建一些东西——因此测试一下:

Post.count.should==1

然后你就知道一篇文章是否被创建了,而不取决于它是如何创建的

编辑#2(嗯…)


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

编辑-扔掉以前的垃圾

这应该是你想要的

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自己的mocking库,并且安装了rspec_rails gem。

谢谢,但这不是我想要实现的。我想做的是检查一个模型类是否收到了某个消息(比如:find、:create等等)