Shopify控制器的Rspec?认证时卡在302上

问题描述 投票:0回答:1

我的项目是一个Rails 5.2应用,运行Ruby 2.6,使用了 shopify_gemfactory_bot_rails.

我有一个控制器,继承自 ShopifyController. 我对控制器的单元测试卡在了302。我无法理解如何通过认证......

我试过这些教程和其他链接,但没有成功。

我的控制器测试如下

require 'rails_helper'

describe OnboardingController, type: :controller do

  before do
    shop = FactoryBot.create(:shop)

    request.env['rack.url_scheme'] = 'https'
    @request.session[:shopify] = shop.id
    @request.session[:shopify_domain] = shop.shopify_domain
  end

   it 'onboards correctly', :focus do
    get :onboard_completed
    expect(response).to have_http_status(:success)
   end

end

我也在玩这个代码,但失败了(注释中的错误)。

module ShopifyHelper

  def login(shop)
    OmniAuth.config.test_mode = true
    OmniAuth.config.add_mock(:shopify,
      provider: 'shopify',
      uid: shop.shopify_domain,
      credentials: { token: shop.shopify_token })
    Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:shopify]

    get "/auth/shopify" # this leads to a UrlGenerationError
    follow_redirect! # this is an undefined method. Seems to be a MiniTest thing

  end

end
ruby-on-rails rspec shopify
1个回答
0
投票
require 'rails_helper'

RSpec.describe "Home", type: :request do
  def login(shop)
    OmniAuth.config.test_mode = true
    OmniAuth.config.add_mock(:shopify,
      provider: 'shopify',
      uid: shop.shopify_domain,
      credentials: { token: shop.shopify_token })
    Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:shopify]

    get "/auth/shopify"
    follow_redirect!

    @request.session[:shopify] = shop.id
    @request.session[:shopify_domain] = shop.shopify_domain
  end

  describe "GET /" do
    it "works!" do

      shop = Shop.first || create(:shop)

      login(shop)
      get root_path

      shop.with_shopify!

      expect(assigns(:products)).to eq ShopifyAPI::Product.find(:all, params: { limit: 10 })
      expect(response).to render_template(:index)
      expect(response).to have_http_status(200)
    end
  end
end

类似这样的东西对我来说是有效的,你在你的函数中出现错误可能是因为你没有在你的ShopifyHelper模块上下文中定义get和follow_redirect!函数。

参考文献: http:/www.codeshopify.comblog_poststesting-shopify-authenticated-controllers-with-rspec-rails


0
投票

这最终成为工作解决方案


require 'rails_helper'

describe WizardController, type: :controller do

  before do
    shop = FactoryBot.create(:shop)

    request.env['rack.url_scheme'] = 'https'
    allow(shop).to receive(:wizard_completed?).and_return(false)
    allow(Shop).to receive(:current_shop).and_return(shop)

    # @note: my original code had "session[:shopify]" of "session[:shop]", which was the error
    session[:shop_id] = shop.id
    session[:shopify_domain] = shop.shopify_domain
  end

  it 'enter test here', :focus do
    get :wizard
    expect(response).to have_http_status(:success)
  end

end

© www.soinside.com 2019 - 2024. All rights reserved.