Laravel Cashier - 使用付款方式创建订阅的单元测试

goo*_*oon 4 laravel stripe-payments laravel-cashier

更深入地研究这一点,我不确定这是否可能,这很遗憾,因为我正在尝试学习 TDD。

我想通过Billable创建和订阅计划来测试我的模型。

/** @test */
public function an_account_can_subscribe_to_a_plan() {
    $account = factory("App\Account")->create();

    Stripe::setApiKey('key');
    $paymentMethod = PaymentMethod::create([
        'type' => 'card',
        'card' => [
            'number' => '4242424242424242',
            'exp_month' => '2',
            'exp_year' => '2021',
            'cvc' => '314'
        ]
    ]);

    $subscription = $account->newSubscription('default', 'starter')->create($paymentMethod);
    $this->assertTrue( $subscription->valid() );  
}
Run Code Online (Sandbox Code Playgroud)

Laravel Cashier 文档展示了如何通过 Stripe.js 发送令牌,但这不适用于单元测试。

我尝试直接包含 Stripe 库并创建一个PaymentMethod对象,但这也需要我手动设置 API 密钥。现在我收到的错误是我必须验证我的电话号码才能将原始信用卡号发送到 stripe API。

我希望有更好的方法。如何以 TDD 方式使用 Laravel Cashier 并使用虚假付款方式模拟虚假订阅?

goo*_*oon 8

Stripe 不仅提供测试卡号,还提供令牌和支付方式。

https://stripe.com/docs/testing#cards

单击付款方式选项卡。值(例如pm_card_visa)可以在您的测试中直接在服务器端使用,无需前端支付意图实现。

这是我的功能测试的一个示例:

    /**
     * @test
     */
    public function a_user_can_subscribe_to_a_paid_plan()
    {

        $this->actingAs($this->user);
        $this->setUpBilling();

        $enterprise = Plan::where('name', 'Enterprise')->first()->stripe_plan_id;

        $response = $this->post(route('paywall.payment'), [
            'payment_method' => 'pm_card_visa',
            'stripe_plan_id' => $enterprise
        ])
        ->assertSessionDoesntHaveErrors()
        ->assertRedirect();

    }
Run Code Online (Sandbox Code Playgroud)

您的测试可能会有所不同,但您可以使用这些测试付款方式向计费控制器发出正常请求,并且其处理过程就像您在前端执行操作一样。