如何通过Rspec测试has_many? [早该-匹配器]

时间:2015-10-21 03:03:37

标签: ruby-on-rails ruby rspec dtd shoulda

我正在尝试使用rails来开发一个rest api。我正在使用rspec和shoulda-matchers。问题是我的一个测试总是失败。

如何更正我的代码,以便测试通过(绿色)。

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

终端

➜  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

1 个答案:

答案 0 :(得分:1)

您必须在usercard工厂中正确设置模型之间的关联。

factory :card do
  # ...
  association :user
end

然后,它应该工作。

请参阅this以了解有关工厂女孩的关联的更多信息。

如果上述方法无法解决您的问题,请尝试这样做:

# spec/factories/user.rb

Factory.define :user, :class => User do |u|
    u.cards { |c| [c.association(:card)] }
end