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?
Example Controller:
class TaskController
def next
if(Tasks.assign_random_test?)
Tasks.next_test
else
Tasks.next_task
end
end
end
ActiveRecord Model:
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.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
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.