Laravel, Behat, Faker and GuzzleHttp - DB Rollback before I can get the data - laravel

I'm try to create a fake data for testing, and have the following code on the Behat Context
$modelFake = factory(User::class)->create();
$client = new GuzzleHttp\Client();
$res = $client->request('GET', url($this->apiURL . '/user/' . $modelFake->id));
After the class declaration I have:
use DatabaseTransactions;
The user fake it's created and I get the current Id to do the request, but the code return an empty object, If I remove the use DatabaseTransactions; the user persist on the database and the request return the object, but I can't realize what is my issue.
I hope someone can help me with this.
Regards
Edit:
When I try to get the user User::find($modelFake->id) I'm getting the object :(
Why when I made the request I can't get the object?
Edit 2:
The main problem it's the data persist only on the context and the request belong to another instance of the DB

Related

View Share doesn't return updated data, how then to share live data?

I currently have a model which access data like so:
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
return view('layouts.cart')->with('cartDetails', $displayCart);
This model correctly retrieves the data in a current session.
To access this same data in a header file I'm using View::Share in the AppServiceProvider like so:
public funciton boot()
{
$currentSessionID = session()->getId();
$inCartDetails = Cart::where('session_id', $currentSessionID)->get();
View::share('inCartDetails', $inCartDetails);
}
In my blade the $inCartDetails returns empty. I get [].
My suspicion is that this function ONLY gets called at boot. Hence the name :) and that it's empty cause at the time of starting the session it's empty since user hasn't selected anything. If this is correct how would I then pass live data to multiple views?
The session is not available in the boot method of the service providers. You should create a middleware for this. Check out this answer here: How to retrieve session data in service providers in laravel?

How to Check if Session is set in Laravel 5.7

<?php
$request = request();
// if (empty($request)) return false; .// That does not work
$loggedUserAccessGroups = $request->session()->get('loggedUserAccessGroups');
$logged_user_ip = $request->session()->get('logged_user_ip');
In my Laravel 5.7 application, I want to check if the user has the right access level in the session. It works ok but I made automatic tests and got the error:
local.ERROR: Session store not set on request.
I added checks to see if the session is set and it fails to return false.
Which is the correct way? Thanks!
You may also use the global session PHP function to retrieve and store data in the session as outlined here:
// Retrieve a piece of data from the session with the global session helper...
$loggedUserAccessGroups = session('loggedUserAccessGroups');
$logged_user_ip = session('logged_user_ip');
// Store a piece of data in the session...
session(['key' => 'value']);
For more information look at the section of The Global Session Helper in the official documentation.

Laravel Stripe Mocking

How can we mock Stripe in Laravel Unit Tests without using any external package like stripe-mock etc?
The job is to test the Controller feature where the secret is hardcoded and due to which test is failing.
Hey i ran into the same problem,
i am using aspectmock from codeception. Gave me some grief setting it up but im now able to mock all the responses with a json response. this way the json data goes thru the stripe classes and it throws the correct errors and returns the same objects.
hope that helps
https://github.com/Codeception/AspectMock
public function testAll()
{
$customerClass = new StripeCustomers();
test::double('Stripe\HttpClient\CurlClient', ['request' => [json_encode($this->allJsonData), 200, []]]);
$customer = $customerClass->all();
$this->assertArrayHasKey('data', $customer);
}

Laravel How to store extra data/value in session Laravel

I'm using default auth() in laravel login (email & password)
Now i try to take input from the user in text field like (Age or City)
Now i want to store (Age/City) in my session.
Help me
You can use session() helper:
session('age', 18); // saves age into session
$age = session('age')`; // gets age from session
Update
If you want to save Age and City after user registration, you should store this data in a DB, not in a session. You can add some fileds in create method of app\Http\Controllers\Auth\AuthController.php
You can use
Session::put('key', 'value');
To get key from Session use
Session::get('key');
You can use the session() helper function as #Alexey Mezenin answer.
Laravel Session Documentation
Ok let me enlighten you. if you want to store it in session do it this way.
session('country', $user->country); // save
$country = session('country')`; // retrieve
But that is not the way we do in Laravel like frameworks, it uses models
once the user is authenticated each time when we refresh the page, application looks for the database users table whether the user exists in the table. the authenticated user model is a user model too. so through it we can extract any column. first thing is add extra fields to the User class(Model) $fillable array.
so it would look something like this.
User.php
protected $fillable = ['username', 'password', 'remember_token', 'country'];
so after simply logging in with user name and password in anywhere just use Request class or Auth facade. Facades are not too recommended so here for your good as a new one i would just say how to use Request. Suppose you want to retrieve your Authenticated user country inside TestController.php here is how it could be used in the methods.
TestController.php
use Illuminate\Http\Request;
public function testMethod(Request $request)
{
$someCountry = $request->user()->country; //gets the logged in user country
dd($someCountry); //dd is die and dump, could be used for debugging purposes like var_dump() method
}
Using Request
public function ControllerName (Request $request){
$request->session()->put('session_age', $age);
}
Get session_age
$get_session_age = $request->session()->get('session_age');
Using Session
public function ControllerName (){
Session::put('age',$age);
}
Get the session
$session_age = Session::get('age');
Don't forget to define Session or Request in your controller!!!
use App\Http\Requests;
use Session;
To work with session in your controller you need to include session first in your controller
use Session;
After that for store data in session. There is several ways to do it. I prefer this one (in controller)
session()->put('key',$value);
To display session data in your View you can do it like this
#if(Session::has('key'))
I'v got session data
#else
I don't have session data
#endif
To get session data in your Controller you can do it like this
session()->get('key')
//or
session()->get('key','defaul_value_if_session_dont_exist')
When you are done with your data in session you can delete it like this (in controller)
session()->forget('key');
All this basic usage of session is well documented in official Laravel documentation here.
Hope it helps you

Zend Framework 2 Unit testing controllers, POST/GET data not sending. Undefined Index

I have been trying to test my controllers as per this tutorial -> Zend Framework 2.1 Unit testing
I have tried every possible variation of the code to send POST or GET data along with the dispatch but the only thing I get back from running the test is "Undefined Index" when I try to access that data from the $_POST array in the controller.
I am using PHPUnit 3.7.17, Everything else works perfectly except for POST and GET data, I have tried the following code:
public function testIndexActionCanBeAccessed() {
$this->getRequest()
->setMethod("POST")
->setPost(new \Zend\Stdlib\Parameters(array('argument' => 'value')));
$response = $this->dispatch('/app/api/index');
$this->assertResponseStatusCode(200);
}
AND
public function testIndexActionCanBeAccessed() {
$post_data = array("argument" => "value");
$response = $this->dispatch("/app/api/index", "POST", $post_data);
$this->assertResponseStatusCode(200);
}
I can't find any help on the web how to fix this issue. Can anyone help out? Any ideas?
$p = new Parameters();
$p->set('username','foo');
$p->set('password','bar');
$this->getRequest()->setMethod('POST');
$this->getRequest()->setPost($p);
$this->dispatch('/login');
This works for me. The Parameters() constructor doesn't seem to be what you're expecting it to be.
The docs say it takes an array, but I could only get it to work this way. The Stdlib\Parameters() constructor doesn't seem to do anything with the array passed in.
Get/Post data not sending, this issue is related to server, can you check the function use for fetching data from server.

Resources