Reputation: 91
I´m trying rails to develop a rest api. I´m using rspec and shoulda-matchers. The problem is that one of my test always fails.
How can I correct my code, so the test passes (GREEN).
user.rb
class User < ActiveRecord::Base
has_many :cards
end
card.rb
class Card < ActiveRecord::Base
belongs_to :user
end
user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
before { @user = FactoryGirl.create(:user) }
subject{ @user }
# Columns
it { should respond_to :name }
# Associations
it { should have_many :cards }
end
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.2.0'
gem 'rails-api'
gem 'spring', :group => :development
gem 'sqlite3'
group :development, :test do
gem 'factory_girl_rails'
gem 'rspec-rails', '~> 3.0'
gem 'shoulda-matchers', '~> 3.0'
end
Terminal
➜ my_api rspec spec/models/user_spec.rb
.F
Failures:
1) User should have many :cards
Failure/Error: it { should have_many :cards }
expected #<User:0x007f897ce0c0d8> to respond to `has_many?`
# ./spec/models/user_spec.rb:12:in `block (2 levels) in <top (required)>'
Finished in 0.04623 seconds (files took 2.45 seconds to load)
2 examples, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:12 # User should have many :cards
Upvotes: 4
Views: 2720
Reputation: 34338
You have to setup the association between the models properly in your user
and card
factories.
factory :card do
# ...
association :user
end
Then, it should work.
See this to know more about associations in factory-girl.
If the above doesn't fix your problem, try doing this way:
# spec/factories/user.rb
Factory.define :user, :class => User do |u|
u.cards { |c| [c.association(:card)] }
end
Upvotes: 1