【问题标题】:rspec stub variable in controller控制器中的 rspec 存根变量
【发布时间】:2015-04-17 19:59:01
【问题描述】:

我想测试一个动作表单控制器,在我的动作中我有这样的东西

def my_action
  @user_collection = DB.get("users")
  users = @user_collection.find({"name" => "123"})
  result_hash = {}
  users.each do |user|
    # populate result_hash here
  end

  render :json => result_hash
end

现在我想用一些测试值替换用户哈希/数组并检查 json 输出,

我尝试过这种方式(规范)

controller.stub!(:users).and_return(my_users_arr)
get :my_action

response.body.should == {1 => 3}

但我得到了这个错误: 未定义的方法“存根!”对于“我的控制器:0x007fde91fd0418”

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    你'stubing'它是错误的。从重构控制器代码开始:

    def my_action
      render :json => users_hash
    end
    
    
    def users_hash
      result = {}
      # generate users hash 
      # ...
      result
    end
    

    然后,在测试方法中试试这个:

    controller.stub!(:users_hash).and_return(my_users_hash)
    get :my_action
    ...
    

    【讨论】:

    • 谢谢,但还有另一种方法可以在我的操作中“伪造”变量吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2013-07-28
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多