如何使用 rspec 和 FactoryGirl 测试子域重定向

how to test subdomain redirect with rspec and FactoryGirl

我正在学习 rspec 并尝试在创建时测试我的帐户控制器。用户创建帐户后(即选择名称和子域),他将被重定向到新子域上的登录页面。

我的测试returnsNoMethodError: undefined method 'subdomain' for #<Hash:0x00000107888c88>

我的帐户工厂设置为生成子域,因此我没有发现我的逻辑有问题。只是语法问题吗?

accounts_controller.rb
class AccountsController < ApplicationController
  skip_before_filter :authenticate_user!, only: [:new, :create]
  def create
    @account = Account.new(account_params)
    respond_to do |format|
      if @account.save
        format.html { redirect_to new_user_session_url(subdomain: @account.subdomain, mp: 'signup' ) }
      else
        format.html { render action: 'new' }
        format.json { render json: @account.errors, status: :unprocessable_entity }
      end
    end
  end
end

/specs/controlles/accounts_controller_spec.rb
require 'rails_helper'
RSpec.describe AccountsController, :type => :controller do
  describe "POST #create" do
    context "with valid attributes" do
      before :each do
        @account = FactoryGirl.attributes_for(:account).merge( owner_attributes: FactoryGirl.attributes_for(:owner) )
      end

      it "redirects to the account subdomain login page" do
        expect(post :create, account: @account).to redirect_to new_user_session_url(:subdomain => @account.subdomain)
      end
    end

    context "with invalid attributes" do
      it "does not save the new account in the database"
      it "re-renders the :new template"
    end
  end
end

在您的测试中,@account 是帐户属性的哈希值

@account = FactoryGirl.attributes_for(:account).merge( owner_attributes: FactoryGirl.attributes_for(:owner) )

上面的行 returns 您在发出请求时作为参数传递的哈希值

你可能应该做 account[:subdomain]

expect(post :create, account: @account).to redirect_to new_user_session_url(:subdomain => @account[:subdomain])