使用 rspec 测试无表模型

发布于 2024-12-17 19:44:45 字数 1101 浏览 0 评论 0原文

我想测试一个没有相应表格的模型。这是模型:

class ContactMessage

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :sender_name, :sender_email, :subject, :content, :recipient_name, :recipient_email

  validates_presence_of :sender_name
  validates_format_of :sender_email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,}$/i
  validates_presence_of :subject
  validates_length_of :content, :minimum => 10

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

  def sender
    sender_name + " <" + sender_email + ">"
  end

  def recipient
    if recipient_name
      recipient_name + " <" + recipient_email + ">"
    else
      recipient_email
    end
  end

end

...但是当我尝试对其运行标准模型测试时,例如:

it { should validate_presence_of :sender_email }

...我得到的回报是:

undefined method `reflect_on_association' for ContactMessage:Class

如何设置这些测试?

I wanted to test a model without a corresponding table. Here is the model:

class ContactMessage

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :sender_name, :sender_email, :subject, :content, :recipient_name, :recipient_email

  validates_presence_of :sender_name
  validates_format_of :sender_email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,}$/i
  validates_presence_of :subject
  validates_length_of :content, :minimum => 10

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

  def sender
    sender_name + " <" + sender_email + ">"
  end

  def recipient
    if recipient_name
      recipient_name + " <" + recipient_email + ">"
    else
      recipient_email
    end
  end

end

...but when I try to run standard model tests on it such as:

it { should validate_presence_of :sender_email }

...I get in return:

undefined method `reflect_on_association' for ContactMessage:Class

How can I set up these tests?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文