RSpec - 功能测试 - 语法检查

时间:2016-03-01 11:36:54

标签: ruby-on-rails ruby rspec devise

所以我正在为我的UserController编写一个Test,以及相关的Devise依赖。

我试图编写一个测试,验证用户A无法访问userB的显示页面,但是会被重定向到root_path。我猜错了语法错误是我的问题,但我喜欢另一双眼睛!

require 'rails_helper'

describe UsersController, :type => :controller do 

  # create test user
    before do
        @userA = User.create!(email: "test@example.com", password: "1234567890")
        @userB = User.create!(email: "test2@example.com", password: "1234567890")
    end

    describe "GET #show" do
        before do
            sign_in(@userA)
        end

        context "Loads correct user details" do
            get :show
            expect(response).to have_http_status(200)
            expect(assigns(:user)).to eq @userA
        end

        context "No user is logged in" do 
            it "redirects to login" do
                get :show, id: @userA.id
                expect(response).to redirect_to(root_path)
            end
        end
    end

    describe "GET Unauthorized page" do
        before do
            sign_in(@userA)
        end

        context "Attempt to access show page of UserB" do
            it "redirects to login" do 
                get :show, id: @userB.id
                expect(response).to have_http_status(401)
                expect(response).to redirect_to(root_path)
            end
        end
    end

end

1 个答案:

答案 0 :(得分:1)

你错过了

中的“it”区块
    context "Loads correct user details" do
        get :show
        expect(response).to have_http_status(200)
        expect(assigns(:user)).to eq @userA
    end