Reputation: 979
Models:
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
The default for role is "member"
In the console I can type:
> @role = Role.find(1)
> @role.position
=> "member"
But in my Rspec tests, I use FactoryGirl to create a user, network, and role. And I have the test @role.should respond_to(:position)
I have also tried just assigning it @role.position = "admin"
. And no matter what, I get an error like:
Failure/Error: @role.should respond_to(:position)
expected [#<Role id:1, user_id: 1, position: "member", created_at...updated_at...>] to respond to :position
Am I missing something very basic?
EDIT:
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
Upvotes: 0
Views: 407
Reputation: 1044
Jesse is correct in his comment, hopefully he will come back and write it as an answer, in the meantime, the code should be:
@role = Role.where(:user_id => @user.id, :network_id => @network.id).first
or
@role = Role.find_by_user_id_and_network_id(@user.id, @network.id)
As an aside, it seems a little odd to be testing the role class in the network controller spec (unless this is just an exploratory test to work out why things aren't working as expected).
Upvotes: 1