2011-03-30 27 views
2

我正在使用rspec來測試使用聲明瞭attr_accessible的模型的控制器。我不想測試attr_accesible在工作(我的模型規範是這樣做的),但我確實想確保我的控制器沒有進行大規模分配。如何編寫rspec控制器規範model_mock佔帳戶沒有海量分配

具體而言,我有一個模型,像這樣:

class Post < ActiveRecord::Base 
    attr_accessible :body 
    validates :body, :presence => true, 
    validates :user, :presence => true 
    belongs_to :user 
end 

和稍微調整了產生控制器(除去XML格式行):

def create 
    # this line keeps the rspec test mock happy 
    @post = Post.new(params[:post].merge(:user => current_user)) 

    # Below are the correct lines of code for runtime for attr_accessible 
    # @post = Post.new(params[:post]) 
    # @post.user = current_user    

    respond_to do |format| 
     if @post.save 
     format.html { redirect_to(@post, :notice => 'Post was successfully created.') } 
     else 
     format.html { render :action => "new" } 
     end 
    end 
    end 

我有一個模擬控制器rspec的測試通過以上:

describe "POST create" do 
    describe "with valid params" do 
    it "assigns a newly created post as @post" do 
     Post.stub(:new). 
     with({'body' => 'hi there', 'user' => @user}) { mock_post(:save => true) } 
     post :create, :post => {'body' => 'hi there'} 
     assigns(:post).should be(mock_post) 
    end 
    end 
end 

我想要做的是改變rspec測試,以便將當我註釋掉第一個@post行並取消註釋以下兩個@post行時,正確驗證控制器。這樣,我將驗證控制器是否能夠正確使用真實模型,但是我可以繼續使用mock進行測試。我已經嘗試了幾種方法,並似乎在圈子裏(好的,我是Rails和Rspect的新手:p)

非常感謝提前!

回答

3

檢查質量分配。你需要複製它。所以在請求發送錯誤的用戶ID

post :create, :post => {'body' => 'hi there', 'user_id' => '2'} 

然後確保您已創建的帖子有由控制器分配(假設它的ID是不是2在這個例子中)

assigns(:post)user_id.should be(current_user.id) 
+0

確保USER_ID,這將使rspec很高興,但它會測試我的控制器代碼沒有使用質量分配? – mm2001 2011-03-30 03:33:08

+0

啊,錯過了海量的作業參考。改變了答案 – giladbu 2011-03-30 06:38:37

相關問題