无法通过Rspec访问属性

时间:2012-07-20 02:57:44

标签: ruby-on-rails 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

1 个答案:

答案 0 :(得分: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)

顺便说一下,在网络控制器规范中测试角色类似乎有点奇怪(除非这只是一个探索性测试,以找出事情没有按预期工作的原因)。