如何测试double,mock或stub控制器端对象

时间:2016-11-20 20:15:25

标签: ruby-on-rails minitest

我正在编写控制器测试,我想验证Controller1的call_dashboard_function。

class Controller1 < ApplicationController 
  before_action :init_dashb

  def call_dashboard_function
     @dashb.do_something!
  end 

  def init_dashb
    @dashb ||= Dashboard.new(current_user)
  end 
end 

class Dashboard
  #... this is a facade class
end 

实际测试:

  test "should do something" do 
    sign_in @user
    patch :call_dashboard_function
  end 

问题是我不想测试仪表板类,因为我有一个单独的测试。所以我想模拟,存根等等这种类行为

如果我从外面访问,那将很容易。但我无法从控制器外部看到仪表板类。

1 个答案:

答案 0 :(得分:1)

你应stub

let(user) { double('user') } # if you don't need real user
# or
let(user) { create(:user) } # if you need real user

before { allow_any_instance_of(Dashboard).to receive(:current_user) { user } }