gpt4 book ai didi

ruby-on-rails - 如何通过 Rspec 测试 has_many? [Shoulda-matchers]

转载 作者:行者123 更新时间:2023-12-02 03:21:12 24 4
gpt4 key购买 nike

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

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

用户名

class User < ActiveRecord::Base
has_many :cards
end


class Card < ActiveRecord::Base
belongs_to :user
end

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

最佳答案

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

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

关于ruby-on-rails - 如何通过 Rspec 测试 has_many? [Shoulda-matchers],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com