我对rails很新,我无法弄清楚如何修复这个bug。 所以这是我的模特:
用户
class User < ActiveRecord::Base
before_save { email.downcase! }
has_many :tickets
has_many :events, through: :tickets
validates :first_name, presence: true
validates :last_name, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255},
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
end
事件:
class Event < ActiveRecord::Base
has_many :tickets
has_many :users, through: :tickets
validates :event_title, presence: true
validates :event_place, presence: true
validates :event_description, presence: true
validates :event_date, presence: true
validates_numericality_of :event_number_tickets, presence: true, numericality: { only_integer: true }, greater_than: 0
end
票:
class Ticket < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
我有一张票据的测试文件
require 'test_helper'
class TicketTest < ActiveSupport::TestCase
def setup
@user = User.new(first_name: "Example", last_name: "User")
@event = Event.new(event_title: "Example Event",
event_place: "123 Example Ave.",
event_description: "Our example event for children to get introduced to technology",
event_date: DateTime.now,
event_number_tickets: 30)
@ticket = Ticket.new(event: @event, ticket_type: "regular", number_of_children: 1)
@user.tickets << @ticket
end
test "should be valid" do
assert @user.tickets.valid?
end
end
每当我运行此测试时,我都会收到以下错误:
NoMethodError: undefined method `valid?' for #<Ticket::ActiveRecord_Associations_CollectionProxy:0x007fae767617c8>
test/models/ticket_test.rb:18:in `block in <class:TicketTest>'
我是否必须为此特定示例创建自定义有效方法。
答案 0 :(得分:1)
ActiveRecord集合不是valid?
方法。如果您正在尝试测试您创建的最后一张故障单是否有效,则可以执行assert @ticket.valid?
之类的操作。
我认为您可能在设置方法中做了太多工作。您可以尝试在设置中设置用户和事件模型,并将您描述的其余部分分解为不同的测试块。