RSpec double/stubs Flashcards
How to stub value and return something?
before do # it calls stub allow(animal).to receive(:name).and_return('hello') end
it { expect(animal.name).to eq ‘hello’ }
How to mock values with expectations?
# it calls mock expect(animal).to receive(:name).and_return('hello')
How to create spy?
allow(thing).to receive(:name).and_return("Fred") # body of test expect(thing).to have_received(:name)
What are the full doubles
?
Full double - entire objects that exist only to be
stubs
What is partial doubles
?
Partial doubles - can stub specific methods of existing
objects.
How to create a full double?
let(:animal) { double(‘Optional name’, name: ‘hello’, age: 10) }
it { expect(animal.name).to eq ‘hello’ }
How to return double itself if double does implement this method? ( 2 methods)
1) spy(‘Name’)
2) double(‘Optional name’).as_null_object
What double types do you know? And what is the difference between them?
# allows any argument double('Project', name2: 'dd' ) 1) double # allows to send only existing instance methods instance_double('Project', name: 'dd' ) 2) instance_double # allows to send only existing class methods instance_double('Project', name: 'dd' ) 3) class_double # take an instance of obejct as the first argument object_double(Project.new, name: 'dd' ) 4) object_double
How to stub any instance of an object?
allow_any_instance_of(Project).to receive(:name).and_return(false)
How to stub exception raising?
allow(animal).to receive(:name).and_raise(‘Error’)
How to check that we run an object method twice?
expect(proj).to receive(:name).twice
How to check that the object method doesn’t invoke?
expect(proj).not_to receive(:name)
How to stub method with argument?
allow(animal).to receive(:name).with(1)
How to stub method and call original?
allow(animal).to receive(:name).and_call_original
How to check that we invoke something with a hash?
expect(animal).to receive(:name).with(a_hash_including(name: ‘Sample’))