require 'rails_helper' RSpec.describe SessionsController, type: :controller do before :each do @user1 = create(:user) end describe 'POST #create' do # 合法流程校验 context 'with legal account' do before :each do post :create, email: @user1.email, password: @user1.password end it 'should get correct email and password' do actual_email = @user1.email actual_password = @user1.password expect(controller.params[:email]).to eq(actual_email) expect(controller.params[:password]).to eq(actual_password) end it 'should authenticate success' do expect(controller.session[:user_id]).to eq @user1.id end it 'should get ok and text: ok' do expect(response).to have_http_status :ok expect(response.body).to eq 'ok' end end # 非法参数测试 context 'with illegal account' do before :each do post :create, email: @user1.email, password: 'wrong_password' end it 'does not authenticate success' do expect(controller.session[:user_id].nil?).to be true end it 'return with 401' do expect(response).to have_http_status :unauthorized expect(response.body).to eq 'account or password is not correct' end it 'should not raise error without param email or password' do expect { post :create, email: @user1.email }.not_to raise_error expect { post :create, password: 'wrong_password' }.not_to raise_error end end end describe 'DELETE #destroy' do it 'should destroy user id in session' do post :create, email:@user1.email, password: @user1.password expect(controller.session[:user_id].nil?).to be false delete :destroy expect(controller.session[:user_id].nil?).to be true end it 'should return 401 without login' do delete :destroy expect(response).to have_http_status :unauthorized end end describe 'GET #show' do context 'after login' do before :each do post :create, email:@user1.email, password: @user1.password get :show, format: 'json' end it 'should render show template' do expect(response).to render_template 'show' end it 'should return user in json' do userInfo = assigns[:current_user] expect(userInfo.id).to eq @user1.id end end it 'should renturn 401 without login' do get :show, format: 'json' expect(response).to have_http_status :unauthorized end end end