skip to Main Content

How can I make the get request load with its session id as what is initially created with $sessionId = session()->getId();

public function test_chatbot_messages_page_has_non_empty_chat(): void
{
    $sessionId = session()->getId();

    ChatbotMessage::create([
        'session_id' => $sessionId,
        'content' => 'Hello',
        'role' => 'You',
    ]);

    ChatbotMessage::create([
        'session_id' => $sessionId,
        'content' => 'Hi there',
        'role' => 'Bot',
    ]);

    $response = $this->get(route('chatbot-messages.index'));

    $response->assertSee('Hello');
}

Index method of the above route

 public function index()
  {
    $conversationHistory = ChatbotMessage::select(['content', 'role'])
      ->where('session_id', session()
        ->getId())
      ->get();

    return view('chatbot-messages.index', compact('conversationHistory'));
  }

2

Answers


  1. Chosen as BEST ANSWER

    I was able to find a solution. This is what worked for me.

      public function test_chatbot_messages_page_has_non_empty_chat()
      {
        $sessionId = session()->getId();
        $sessionName = session()->getName();
    
        $userMessage = ChatbotMessage::create([
          'session_id' => $sessionId,
          'content' => 'Hello',
          'role' => 'You'
        ]);
    
        $chatbotMessage = ChatbotMessage::create([
          'session_id' => $sessionId,
          'content' => 'Hi there',
          'role' => 'Bot'
        ]);
    
        $response = $this->withCookies([$sessionName => $sessionId])
                         ->get(route('chatbot-messages.index'));
    
        $response->assertViewHas('conversationHistory', function ($collection) use ($userMessage, $chatbotMessage) {
          return $collection->contains('content', $userMessage['content'])
            && $collection->contains('content', $chatbotMessage['content'])
            && $collection->contains('role', $userMessage['role'])
            && $collection->contains('role', $chatbotMessage['role']);
        });
    

  2. Maybe try to using session()->setId($sessionId), you set the session ID for the test session to match the one you created initially. This way, when you make the GET request in your test, it will use the same session ID, and your index method will retrieve the chat history associated with that session.

    // Set the session ID for the test session
    session()->setId($sessionId);
    
    $response = $this->get(route('chatbot-messages.index'));
    
    $response->assertSee('Hello');
    

    But I’m not sure if you were thinking about that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search