2012-04-09 63 views
0

如何RSpec的糾正這種錯誤控制器,如何測試Rspec的對於控制器,

1)SellersController GET索引找到活動 故障/錯誤:分配(:活性)。應該當量([活性])

expected: [#<Activity id: 65, transactable_type: "admin", transactable_id: 1, action_type: "seller", user_id: 1, is_approved: false, approved_by: nil, created_at: "2012-04-09 11:02:17", updated_at: "2012-04-09 11:02:17", associatable_type: nil, associatable_id: nil>] 
     got: nil 

    (compared using ==) 

Seller_rspec.rb

describe "GET index" do 
    it "find the Activity" do 
activity = Activity.create!(:transactable_type=>"admin",:transactable_id=>1,:action_type=>"seller",:user_id =>1,:is_approved=>0) 
    get :index,{:is_approved => activity.to_param,:user_id=>1,:approved_by=>"admin"} 
    assigns(:activity).should eq([activity]) 
    end 

在控制器

def index 
     @activities=Activity.find(:all,:select => 'DISTINCT transactable_type,transactable_id,action_type,is_approved,approved_by',:conditions=>["is_approved= ? and user_id=? and approved_by IS NULL",false,current_user.id]) 
    end 

回答

0

您正在將代碼放入控制器中,該代碼應該轉到模型中。創建樣活性模型的方法和範圍:

def self.find_not_approved(current_user_id) 
     find(:all, 
      :select => 'DISTINCT transactable_type,transactable_id,action_type,is_approved,approved_by', 
      :conditions= ["is_approved= ? and user_id=? and approved_by IS NULL", 
      false, 
      current_user_id]) 
end 

所以,你可以在控制器(我做了方法名):

def index 
    @activities = Activity.find_not_appoved(current_user.id) 
    end 

而只是爲了你的問題,應該是assigns(:activities).should eq([activity])而不是assigns(:activity).should eq([activity]) - 因爲您正在檢查控制器中的@activities變量而非@activity。

+0

所以......它工作? :P – Ernest 2012-04-11 09:16:19