SD1990
SD1990

Reputation: 808

rspec testing a nested if function

IM very new to rspec testing and need alittle bit of help.

Im testing a controller for my timesheet and im trying to test this piece of code.

if params[:user_id] == nil
      if current_user == nil
        redirect_to new_user_session_path
      else
        @user_id = current_user.id
      end
    else
      @user_id = params[:user_id]
    end

im not sure if its even worth testing but it seems theres a lack of tutorials for the beginner out there, so i wouldnt know. thanks in advance

Upvotes: 1

Views: 3054

Answers (1)

Solomon
Solomon

Reputation: 7023

You can do this in rspec using describe statements and before(:each) to setup each scenario and test it

describe "test the controller" do

    before(:each) do
        @user = Factory(:user)
    end

    describe "for non signed in users" do

        it "should redirect to sign in page" do
            get :action
            response.should redirect_to(new_user_session_path)
        end

    end

    describe "for signed in users" do

        before(:each) do
            sign_in(@user)
        end

        it "should be successful" do
            get :action
            response.should be_success
        end

    end

end

Just use different describe statements and setup each test with before(:each) and you should be fine.

Upvotes: 2

Related Questions