Issue
I am trying to test my BooksController's add method. The condition is that A user needs to be logged in before adding a book. But I am not finding any way to make a user login in the test method.
My code is like this-
public function testAdd()
{
$user = ['email' => 'admin@example.com', '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');
}
The assert is getting failed because I am getting redirected to /users/login.
My login method is like this-
//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.');
}
Is there any way to fix this issue? Thanks in advance!
Solution
That's not how integration tests work, you should not make multiple requests in a single test method, this can easily lead to pollution, as session data, cookies, token config, etc is only being reset after the test method has run, and not inbetween requests.
That being said, emulating a logged in user works by simply adding proper authentication info to the respective storage, or the request. If you're using the session storage, simply add the info to the session before making the request to your add
action:
$this->session([
'Auth' => [
'User' => [
'id' => 1,
'username' => 'foo'
// ...
]
]
]);
See also
- Cookbook > Testing > Controller Integration Testing
- Cookbook > Testing > Controller Integration Testing > Testing Actions That Require Authentication
Answered By - ndm
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.