stub
Using `any_instance` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead
mock return value
# deprecated
any_model.stub(:class_method).and_return(AnyValue)
any_model.any_instance.stub(:instance_method).and_return(AnyValue)
mock exception\/error
# deprecated
any_model.stub(:class_method).and_raise(AnyError)
any_model.any_instance.stub(:instance_method).and_raise(AnyError)
using rspec-mocks
allow(Object).to receive(:method).and_return(AnyValue)
allow_any_instance_of(Class).to receive(:instance_method).and_return(AnyValue)
allow_any_instance_of(Class).to receive(:instance_method).and_raise(AnyError)
#works for private or public method
allow_any_instance_of(described_class).to receive(:private_or_public_method!).and_raise(ActiveRecord::RecordInvalid.new(AnyModel.new))
allow_any_instance_of(Class).to receive_message_chain(:errors, :full_messages).and_return("Error 1", "Error 2")
#examples
allow_any_instance_of(Merchant).to receive_message_chain('user.email') { 'email'}
stub environment variables for unit testing
allow(ENV).to receive(:[]).and_return("123")
allow(ENV).to receive(:[]).and_return(ENV)
allow(ENV).to receive(:[]).with('SPECIFIC_KEY').and_return("FAKE_VALUE")
stub session for controller test without http requests
before do
subject.request = ActionController::TestRequest.new(host: 'https://examplecom/')
subject.request.session[:any_id] = 'AnyValue'
end
Reference
- rspec-mocks
- Testing and Environment Variables
- Issue using RSpec to pass parameters to mocked model method in Rails controller action
- Message Chains
- how to stub the :errors collection to act invalid when rspec tests a controller that uses respond_with
- Raising an error
- How to mock request object for rspec helper tests?
- Message Chains
- How to set private instance variable used within a method test?