簡體   English   中英

Rails / Rspec-如何在控制器測試中添加模型方法?

[英]Rails/Rspec - How to stub a model method inside of a controller test?

我有一個控制器方法,可以隨機返回不同的對象。 我該如何對隨機化方法進行存根處理,使其始終返回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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM