【问题标题】:Laravel Cashier - Unit Tests with creating subscriptions with payment methodsLaravel Cashier - 使用付款方式创建订阅的单元测试
【发布时间】:2020-06-09 09:26:19
【问题描述】:

深入研究,我不确定这是否可能,这很遗憾,因为我正在尝试学习 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() );  
}

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

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

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

【问题讨论】:

    标签: laravel stripe-payments laravel-cashier


    【解决方案1】:

    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();
    
        }
    

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

    【讨论】:

      【解决方案2】:

      您可能希望在测试期间使用stripe-mock 进行模拟。如果这不符合您的需求,mocking the objects directly 可能是更好的选择。

      【讨论】:

      • 谢谢,我得看看嘲讽。在测试方面,这样的伪造数据似乎很奇怪。因为现在您只能确定您的模拟数据有效,但您不能 100% 确定真实世界的数据有效
      猜你喜欢
      • 2021-11-13
      • 2015-05-01
      • 2019-10-22
      • 1970-01-01
      • 2021-02-14
      • 2016-07-02
      • 2021-11-27
      • 1970-01-01
      • 2021-08-19
      相关资源
      最近更新 更多