Search code examples
ruby-on-railsrubyrspecrspec-rails

How to know the flow of the controller method using Rspec


I have two dependent drop down.One gives me orgname and other drop down populates on selecting a orgname, That is teamname.
This is my github_leader_board_spec.rb

describe "github_leader_board" do
    before do
      @obj = DashboardsController.new
    end
    context "with session" do

      subject { get :github_leader_board, :params => { :orgname => "test", :teamname=> "team"}}
      it "returns http success" do
        expect(response).to have_http_status(:success)
      end
      it "executes other functions" do
        expect(@org_data).not_to be_nil
        expect(@obj.get_team_api("DevCenter")).not_to be_nil
      end
    end
  end

This is my controller method

def github_leader_board
        myhash = {}
        @points_hash = {}
        member_data = []
        @org_data = get_org_api
        @orgs = get_names(org_data)
        team_data = get_team_api(params[:orgname])
        @teams = get_names(team_data)
        teamid = get_team_id(team_data)
        @teams.each_with_index {|k,i|myhash[k] = teamid[i]}
        myhash.each do |key,value|
            if key == params[:teamname]
                member_data = get_members("#{value}")
            end
        end
        @memberids = get_names(member_data)
        member_names = get_member_names(@memberids)
        review_comments = get_reviewcoments(@memberids)
        reactions = points(@memberids)
        points = [review_comments, reactions].transpose.map {|x| x.reduce(:+)}
        member_names.each_with_index {|k,i|@points_hash[k] = points[i]}

    end

If i run my spec file it says, undefined @org_data. The function inside the github_leader_board controller is not calling the get_org_api and storing the value to the @org_data variable. Can anybody suggest what is wrong with the code and how can i improve it. As i'm new to ror. Any help would be appreciated. Thank you.


Solution

  • I believe you could use a test of the type controller, instead of instantiating your controller and then use the RSpec method assigns (docs) to test your instance variables, something like this:

    RSpec.describe DashboardsController, :type => :controller do
       context "with session" do
          # ...
          it "executes other functions" do
            expect(assigns(:org_data)).not_to be_nil
          end
        end
    end
    

    https://relishapp.com/rspec/rspec-rails/docs/controller-specs

    Also, if you want to check the flow, and debug your code, you can use the gems pry, pry-rails and pry-nav as @Marek Lipka stated.