class TestController < AplicationController
  #....

  private

  def some_method
    unless @my_variable.nil?
      #...
      return true
    end
  end
end

我想直接在控制器规格中测试some_method:

require 'spec_helper'

describe TestController do
  it "test some_method"
    phone = Phone.new(...)
    controller.assign(:my_variable,phone) #does not work
    controller.send(:some_method).should be_true
  end
end

如何从控制器规范中设置TestController个实例变量@my_variable

推荐答案

在控制器中测试私有方法时,我倾向于使用anonymous controller,而不是使用send,因为我不想直接调用私有方法,而是要调用私有方法的接口(或者,在下面的测试中,有效地中断该接口).所以,在你的情况下,可能是这样的:

require 'spec_helper'

describe TestController do
  controller do
    def test_some_method
      some_method
    end
  end

  describe "a phone test with some_method" do

    subject { controller.test_some_method }

    context "when my_variable is not nil" do
      before { controller.instance_variable_set(:@my_variable, Phone.new(...)) }
      it { should be_true }
    end

    context "when my_variable is nil" do
      before { controller.instance_variable_set(:@my_variable, nil) } 
      it { should_not be_true } # or should be_false or whatever
    end     
  end
end

关于在this StackOverflow Q&A中直接测试私有方法的问题,有一些很好的讨论,这让我倾向于使用匿名控制器,但你的观点可能不同.

Ruby-on-rails相关问答推荐

使用Hotwire/Turbo的Rails在链接悬停时获取请求

Rails 6升级没有加载Mongoid,这是一个问题

轨道强参数,怎么允许空参数?

Rails 7 中的预编译

获取所有属于模型的嵌套对象

在 Rails 6.1 升级后,作业(job)规范使用 Minitest::UnexpectedError 包装错误

如何在 Arel 中重用单个绑定变量?

heroku 推送错误:无法检测到 rake 任务

Ruby的自动代码质量工具?

如何为 Rails SimpleForm Select 框设置默认 Select 值

Rails Mailer Net::OpenTimeout: execution expired 仅在生产服务器上出现异常

activerecord 查找所有未包含在数组中的内容

设计记住我和会话

Rails 5:重命名表迁移

默认呈现 JSON 而不是 HTML?

如何在 Rails 迁移中添加一些插入?

在 Rails 中命名布尔列

设计:为什么我的注销链接不起作用?

将数组传递到 hidden_​​field ROR

在 Rails 4.1 中,如何通过枚举符号查找记录?