【问题标题】:How to check return value of private methods in controller如何检查控制器中私有方法的返回值
【发布时间】:2012-03-26 06:38:19
【问题描述】:

我想用 rspec 测试控制器的私有方法(不是动作)

class FooController < ApplicationController
  def some_methods( var )
    if  var 
      return 1
    else 
      return 2
    end
  end

  def some_action
    var = true
    r = some_methods(var)
    r
  end
end

rspec:

require 'spec_helper'

describe FooController do
   describe "GET index" do
      it "get get return value from some_methods" do
          @controller = TestController.new
          r =@controller.instance_eval{ some_action }  
          r.should eq 2
  end
end

这是我的rspec 代码。但是,r 始终为 1,我不知道如何将参数传递给some_action。 如何使用 rspec 方式验证 some_methods 的实际返回值? (例如:r.should be_nil

引用但不起作用:

  1. Rspec, Rails: how to test private methods of controllers?

  2. How to spec a private method

【问题讨论】:

  • 您尝试了哪些方法,引用的问题对您不起作用怎么办?
  • 我尝试为some_methods 的返回值编写测试。引用问题的解决方案无法确定rspec 的返回值,例如:r.should be_nil
  • 所以你写了一些RSpec代码来测试some_methods的返回值?你能把那个贴出来吗?为什么要专门测试局部变量r的值?
  • 已更新。谢谢。我正在尝试测试 some_methods 的返回值。

标签: ruby-on-rails rspec


【解决方案1】:

我还是有点迷茫。您不应该关心控制器 action 的返回值。动作应该呈现内容,而不是返回有意义的值。不过我还是尽量回答吧。

如果您想确保FooController#some_action 调用带有特定参数的私有方法#some_methods,您可以使用#should_receive

describe FooController do
  describe 'GET index' do
    it 'should get the return value from some_methods' do
      controller.should_receive(:some_methods).with(true).and_return(1)
      get :index
    end
  end
end

如果控制器从未收到消息:some_methods,此示例将失败,但它实际上并没有检查方法#some_action 的返回值(因为这几乎没有意义)。

如果您需要测试#some_methods 的行为,您应该使用您引用的文章中讨论的技术为此编写单独的测试。

【讨论】:

    【解决方案2】:

    您似乎遇到了一些不同的问题:

    1. 为什么 r 总是返回 1? r 总是 1,因为您从 insance_eval 调用 some_actionsome_action 调用 some_methods(true),如果传入 true,some_methods 返回 1。使用您提供的代码,some_action 将始终返回 1

    2. 我猜这些只是拼写错误,但你的类名是 FooController,而你在 rspec 中测试的控制器是 TestController。此外,some_methods 函数未标记为私有。

    3. 如何传递参数,您应该可以直接从您的 instance_eval 块中调用some_methods 并像普通函数调用一样传递参数:

      r = @controller.instance_eval{ some_methods(false) }

      r.should eq 2

    【讨论】:

      【解决方案3】:

      使用 print/puts 语句检查日志或使用调试器“rails-debug”在运行时检查值。

      puts r = some_methods(var)

      【讨论】:

      • 这不是解决方案,抱歉。我认为有一个rspec 解决方案,例如should be_nil ...。
      • 'rspec solution like should be_nil' 是您放入 testcases 的检查。但是如果你想在控制器中查看私有方法的值,那么 1) 在控制器中添加 puts/p/pp 然后检查测试日志。 2)在方法调用之前使用调试器。看看调试器是如何工作的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 2011-07-12
      相关资源
      最近更新 更多