属性无法通过Rspec的访问

问题描述:

型号:属性无法通过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

杰西是他的意见是正确的,希望他会回来,并把它写成一个答案,在此期间, ,代码应该是:

@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