【问题标题】:How to Validate the non active record models in rspec?如何验证 rspec 中的非活动记录模型?
【发布时间】:2015-02-18 12:04:03
【问题描述】:
#item class
class Item
 include ActiveModel::Model
   #validations from activemodel class

    validates :url, presence: true
    validates :text, presence: true 
    attr_accessor :url
    attr_accessor :text    

    def initialize (url,text)
          @url=url
          @text=text
    end 
end
  --------------------------------------------------------

RSpec.describe Item, type: :model do
 before :each do
   @url="www.fb.com"
   @text="to see fb"
   @item=Item.new(@url,@text)
 end

    it { (@item).to validate_presence_of(:url) }

end

它在 rspec 中显示错误 validate_presence_of 我所有剩余的测试都通过了所有验证都显示没有方法错误

【问题讨论】:

  • 您的 Gemfile 中有 shoulda gem 吗? github.com/thoughtbot/shoulda 另外,请问您的代码可以正确缩进吗?
  • 否,如果 gem 有超过 100 个贡献者,我唯一可以使用该 gem。对于缩进,这是我对程序的第一个问题。
  • 感谢编辑,现在好多了。我不明白你对 gem 贡献者的看法。
  • 其复杂的客户要求。无论如何感谢您的建议它工作得很好。
  • 如果没有可用的选项。我将只使用您的建议。我认为它来自 Activerecord。

标签: ruby ruby-on-rails-4 rspec


【解决方案1】:

确保您的Gemfile 中有shoulda gem。检查语法,期望应该是这样的:

describe Item do
  it { is_expected.to validate_presence_of(:url) }
end

【讨论】:

  • 我编辑了新代码,但它显示 ArgumentError: wrong number of arguments (0 for 2)
  • 我在构造函数中更改了没有参数的代码并尝试了 Yours 。但它再次显示没有方法错误
  • 我知道了@dgilperez 建议使用 shoulda gem 有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多