2012-07-20 121 views
0

型號:屬性無法通過Rspec的訪問

class User < ActiveRecord:Base 
    has_many :roles 
    has_many :networks, :through => :roles 
end 

class Network < ActiveRecord:Base 
    has_many :roles 
    has_many :network, :through => :roles 
end 

class Role < ActiveRecord:Base 
    attr_accesible :user_id, :network_id, :position 

    belongs_to :user 
    belongs_to :network 
end 

的角色默認爲 「會員」

在控制檯我可以輸入:

> @role = Role.find(1) 
> @role.position 
=> "member" 

但在我的Rspec的測試中,我使用FactoryGirl創建用戶,網絡和角色。並且我有測試@role.should respond_to(:position)我也嘗試過將它分配給@role.position = "admin"。無論如何,我收到如下錯誤:

Failure/Error: @role.should respond_to(:position) 
    expected [#<Role id:1, user_id: 1, position: "member", created_at...updated_at...>] to respond to :position 

我是否缺少一些非常基本的東西?

編輯:

factories.rb

FactoryGirl.define do 
    factory :user do 
    name    "Example User" 
    sequence(:email) {|n| "email#{n}@program.com"} 
    end 

    factory :network do 
    sequence(:name)  {|n| "Example Network #{n}"} 
    location    "Anywhere, USA" 
    description   "Lorem Ipsum" 
    end 

    factory :role do 
    association :user 
    association :network 
    position    "member" 
    end 

end 

network_controller_spec

... 
before(:each) do 
    @user = test_sign_in(FactoryGirl.create(:user) 
    @network = FactoryGirl.create(:network) 
    @role = FactoryGirl.create(:role, :user_id => @user.id, :network_id = @network.id) 
    #I have also tried without using (_id) I have tried not setting the position in the factories as well. 
end 

it "should respond to position" do 
    get :show, :id => @network 
    # This may not be the best or even correct way to find this. But there should only be one, and this method works in the console. 
    @role = Role.where(:user_id => @user.id, :network_id => @network.id) 
    @role.should respond_to(:position) 
end 
+0

將有助於查看您的完整規範。例如,你如何在rspec中定義'@ role'? – Dty 2012-07-20 03:08:15

+2

它看起來像@role是一個角色數組,而不僅僅是一個角色。你會添加設置@role的代碼嗎? – 2012-07-20 03:46:20

+0

@JesseWolgamott可能是對的。他應該把它寫成答案,所以它可以被標記爲正確的。 – iGEL 2012-07-20 08:41:00

回答

1

傑西是他的意見是正確的,希望他會回來,並把它寫成一個答案,在此期間, ,代碼應該是:

@role = Role.where(:user_id => @user.id, :network_id => @network.id).first 

@role = Role.find_by_user_id_and_network_id(@user.id, @network.id) 

順便說一句,這似乎有點奇怪在網絡控制器規格(被測試的角色類,除非這僅僅是一個探索性的測試工作,爲什麼預期的東西不工作)。

+0

實際上,我真的沒有測試角色類,我測試是否出現銷燬按鈕是基於用戶是否有適當的角色,但由於我無法讓它工作,所以我決定只是爲了測試是否響應':position'。一旦它開始工作,我將使用它進行適當的測試。非常感謝! – dewyze 2012-07-20 18:14:36

+0

如果傑西不發表他的回答,禮儀是什麼?我同時選擇你的嗎?在他發佈之前,我是否從不接受任何內容 – dewyze 2012-07-22 03:20:41

+0

我猜他多給我幾天? – 2012-07-22 20:03:50