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

时间:2015-02-04 19:48:44

标签: ruby-on-rails rspec factory-bot

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

我的测试返回NoMethodError: 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

1 个答案:

答案 0 :(得分:1)

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

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

以上行返回一个哈希值,您在发出请求时将其作为参数传递

你应该做account[:subdomain]

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