简体   繁体   English

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

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

I have a controller method that can return different objects at random. 我有一个控制器方法,可以随机返回不同的对象。 How can I stub out the randomization method so that it always returns true or false so I can test the responses? 我该如何对随机化方法进行存根处理,使其始终返回true或false,以便测试响应?

Example Controller: 控制器示例:

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

ActiveRecord Model: 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 Test 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) 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