0
我想測試我的BooksController的add方法。條件是用戶在添加圖書之前需要先登錄。但我沒有找到任何方法在測試方法中進行用戶登錄。如何測試需要驗證的操作?
我的代碼是像這個 -
public function testAdd()
{
$user = ['email' => '[email protected]', 'password' => 'abcd'];
$this->post('/users/login', $user);
$book = ['title' => 'Foo', 'writer' => 'writer1', 'edition' => '2nd', 'course' => 'CSE', 'description' => 'abcd', 'price' => '200', 'status' => '0', 'user_id' => '1', 'photo' => 'abcd'];
$this->post('/books/add', $book);
$this->assertRedirect('/books');
}
斷言是越來越失敗了,因爲我收到重定向到/用戶/登錄。
我的登錄方法就像是這個 -
//Login Function
public function login()
{
if($this->request->session()->read('Auth.User'))
{
$this->Flash->error(__('You are already logged in.'));
return $this->redirect(['controller' => 'home','action' => 'index']);
}
if($this->request->is('post'))
{
$user = $this->Auth->identify();
if($user)
{
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
}
//In case of bad login
$this->Flash->error('You must login first.');
}
有沒有什麼辦法來解決這個問題? 在此先感謝!
謝謝!你釘了它! –