Aims. We investigate the formation of flux ropes in a flux emergence region and their rise into the outer atmosphere of the Sun. Methods. We perform 3D numerical experiments by solving the time-dependent and resistive MHD equations. Results. A sub-photospheric twisted flux tube rises from the solar interior and expands into the corona. A flux rope is formed within the expanding field, due to shearing and reconnection of field lines at low atmospheric heights. If the tube emerges into a non-magnetized atmosphere, the flux rope rises, but remains confined inside the expanding magnetized volume. In contrast, if the expanding tube is allowed to reconnect with a pre-existing coronal field, the flux rope experiences a full eruption with a rise profile that is in qualitative agreement with erupting filaments and Coronal Mass Ejections.