Reputation: 1006
I'm trying to get around with Rails. It's my first Rails app and I am testing it in a process of evaluation for our future projects. I've followed railstutorial.org all the way up to chapter 9 and then tried to go on my own.
Using Rails 3.2.3,Ruby 1.9.3, Factory Girl 1.4.0 and rspec 2.10.0.
The trouble I'm getting is with a Client--[has_many]-->User relationship.
The error I can't get through when running tests:
1) User
Failure/Error: let(:client) { FactoryGirl.create(:client) }
NoMethodError:
undefined method `user' for #<Client:0x000000045cbfa8>
spec/factories.rb
FactoryGirl.define do
factory :client do
sequence(:company_name) { |n| "Company #{n}" }
sequence(:address) { |n| "#{n} Example Street"}
phone "0-123-456-7890"
end
factory :user do
sequence(:name) { |n| "Person #{n}" }
sequence(:email) { |n| "person_#{n}@example.com"}
password "foobar"
password_confirmation "foobar"
client
factory :admin do
admin true
end
end
spec/models/user_spec.rb
require 'spec_helper'
describe User do
let(:client) { FactoryGirl.create(:client) }
before { @user = client.users.build(name: "Example User",
email: "[email protected]",
password: "foobar",
password_confirmation: "foobar") }
subject { @user }
it { should respond_to(:name) }
end
app/controllers/clients_controller.rb
class ClientsController < ApplicationController
def show
@client = Client.find(params[:id])
end
def new
@client = Client.new
@client.users.build # Initializes an empty user to be used on new form
end
def create
@client = Client.new(params[:client])
if @client.save
flash[:success] = "Welcome!"
redirect_to @client
else
render 'new'
end
end
end
app/controllers/users_controller.rb
class UsersController < ApplicationController
.
.
.
def new
@user = User.new
end
.
.
.
end
app/models/user.rb
class User < ActiveRecord::Base
belongs_to :client
.
.
.
end
app/models/client.rb
class Client < ActiveRecord::Base
has_many :users, dependent: :destroy
.
.
.
end
Thanks for any help !
Upvotes: 2
Views: 2861
Reputation: 27779
In your user_spec you're calling client.users
, but it appears elsewhere that client belongs to user (singular). If so, try something like:
FactoryGirl.define do
factory :client do
...
association :user
end
end
describe User do
let(:user) { FactoryGirl( ... ) }
let(:client) { FactoryGirl(:client, :user => user) }
subject { user }
it { should respond_to(:name) }
end
Upvotes: 2