如何在测试中更新Laravel会话ID

zed5wv10  于 2023-11-20  发布在  其他
关注(0)|答案(2)|浏览(95)

如何使get请求加载时的会话ID与最初使用$sessionId = session()->getId();创建的会话ID相同

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上述route的方法

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

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

mzillmmw

mzillmmw1#

也许可以尝试使用session()->setId($sessionId),你设置测试会话的会话ID来匹配你最初创建的会话ID。这样,当你在测试中发出GET请求时,它将使用相同的会话ID,你的索引方法将检索与该会话相关的聊天历史。

// Set the session ID for the test session
session()->setId($sessionId);

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

$response->assertSee('Hello');

字符串
但我不确定你是否想过这个。

svgewumm

svgewumm2#

我找到了一个解决办法。这对我很有效。

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']);
    });

字符串

相关问题