简体   繁体   中英

How to test double, mock or stub controller side object

I'm writing a controller test, and I wanted to verify Controller1's 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 

Actual test:

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

The problem is I don't want to test the dashboard class, since I have a separated test for it. So I'd like to mock, stub, etc this class behavior

That would be easy if I had access from outside. But I can't see dashboard class from outside the controller.

you should stub it:

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 } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM