【问题标题】:How to pass Rspec test has_many? [Shoulda-matchers]如何通过 Rspec 测试 has_many? [应该匹配者]
【发布时间】:2015-10-21 03:03:36
【问题描述】:

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

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

用户.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

宝石文件

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多