如何测试Rspec对于控制器,

时间:2012-04-09 11:06:19

标签: ruby-on-rails-3.1 rspec

如何在RSpec for Controller中纠正此错误,

1)SellersController GET索引查找Activity      失败/错误:分配(:活动).should eq([activity])

   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

1 个答案:

答案 0 :(得分:0)

您正在将代码放入控制器中,该控制器应该转到模型中。在Activity模型中创建方法或范围,如:

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

只是 anser 你的问题,它应该是assigns(:activities).should eq([activity])而不是assigns(:activity).should eq([activity]) - 因为你正在检查控制器中的@activities变量,而不是@activity。