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)

.and_raise

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

results matching ""

    No results matching ""