【问题标题】:Rails/Rspec - How to stub a model method inside of a controller test?Rails/Rspec - 如何在控制器测试中存根模型方法?
【发布时间】:2019-07-15 19:14:28
【问题描述】:

我有一个控制器方法可以随机返回不同的对象。如何存根随机化方法,使其始终返回 true 或 false,以便我可以测试响应?

示例控制器:

class TaskController
  def next 
    if(Tasks.assign_random_test?)
      Tasks.next_test
    else 
      Tasks.next_task
    end
  end
end

ActiveRecord 模型:

class Tasks << ActiveRecord::Base
  def self.assign_random_test? 
    rand() > 0.899
  end

  def self.next_test
   # ...
  end

  def self.next_task
   # ... 
  end
end

RSpec 测试

RSpec.describe TaskController, type :controller do 
  it 'can return a test task' do 
   # force random method to return true here? 
  end
end

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    allow(Tasks).to receive(:assign_random_test?).and_return(true)

    RSpec.describe TaskController, type :controller do 
      describe '#next' do
        before do
          allow(Tasks).to receive(:assign_random_test?).and_return(true)
        end
    
        context 'when assign_random_test' do
          it 'should return result' do
            #your test here
          end 
        end
    
        context 'when not assign_random_test' do
          before do
            allow(Tasks).to receive(:assign_random_test?).and_return(false)
          end
          it 'should return result' do
            #your test here
          end 
        end
      end 
    end
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 2012-06-27
      • 1970-01-01
      相关资源
      最近更新 更多