2013-03-27 111 views
1

我試圖爲子控制器編寫一些控制器規格,在這種情況下Admin :: UsersControllerRspec控制器與STI用戶模型的測試?

它具有基本的CRUD操作集。

我users_controller_spec.rb

describe Admin::CarriersController do 
    before(:each) do 
    sign_in FactoryGirl.create(:admin) 
    end 

    it "should have a current_user" do 
    subject.current_user.should_not be_nil 
    end 

    describe "GET 'index'" do 
    it "assigns all users as @users" do 
     user = create(:user) 
     get :index 
     assigns(:users).should eq [user] 
    end 
    it "renders the index view" do 
     get :index 
     expect(response).to render_template :index 
    end 
    end 
end 

現在我對跑起來的問題是指數的行動。我的控制器工作,是一個簡單的@users = User.all

請告訴我事情複雜是我的用戶表是這樣STI

class User < ActiveRecord::Base 
end 
class Client < User 
end 
class Seller < User 
end 

我的工廠

FactoryGirl.define do 
    factory :user do 
    name { Faker::Company.name } 
    sequence(:email) {|n| "test#{n}@test.com"} 
    password "password" 
    password_confirmation {|instance| instance.password } 
    type "Seller" 

    factory :admin do 
     type "Admin" 
    end 

    factory :seller do 
     type "Seller" 
    end 

    factory :client do 
     type "Client" 
    end 
    end 
end 

顯然EQ方法是行不通的因爲RSpec在匹配我的分配(:用戶)期望中的類名時遇到了問題。 我的確切錯誤是:

1) Admin::UsersController GET 'index' assigns all users as @users 
    Failure/Error: assigns(:users).should eq user 
     expected #<ActiveRecord::Relation [#<Client id: 1282, name: "Marks-Kozey", type: "Client"...]> to eq #<User id: 1282, name: "Marks-Kozey", type: "Client"... 

我的問題是我的工廠?還是我測試不正確?這是我第一次測試STI,所以任何幫助都是值得讚賞的。

+0

爲什麼不通過工廠而是用戶創建客戶端? – gylaz 2013-03-27 04:29:03

+0

是的,我最終將用戶工廠分成了不同的用戶類型的工廠,但這似乎是一個黑客,因爲它不代表正確的STI,儘管現在工作 – TheIrishGuy 2013-03-27 13:30:56

回答

2

嘗試使類符號到子工廠,例如:

factory :client, class:Client do 
    type "Client" 
end 

然後將工廠生成的對象應該是Client型代替的User的。