2010-04-29 63 views
0

我正在嘗試編寫功能測試。我的測試看起來如下:RSpec:測試控制器時模型不能工作的期望

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 

運行測試我總是接收失敗,它說,郵政類預計:新的,但從來沒有得到它。不過,實際的帖子是被創建的。

我是RSpec的新手。我錯過了什麼嗎?

回答

0

您可以使用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。如果您正在測試除控制器的正確職責以外的其他任何事情,那麼在重構時會冒着破壞測試的風險,並且在實施更改時必須返回並重寫測試。

創建操作的工作是創造的東西 - 這樣的測試爲:

Post.count.should == 1

,然後你知道一個帖子是否被創建,而不依賴於它是如何被創造。

編輯#2(呃......)

我從你的,你已經知道正在創建的帖子原來的問題看。我仍然認爲你應該測試行爲而不是實現,並且檢查模型是否接收到消息在控制器測試中不是一件好事。也許你在做的是調試,而不是測試?

+0

謝謝,但那不是我想要完成的事情。我想要做的是檢查一個模型類是否收到某個消息(如:find,:create等) – gmile 2010-04-30 10:23:31

1

編輯 - 扔掉了以前的垃圾

這應該做你想要

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寶石。