【问题标题】:How to write unit tests to this specific ActiveRecord class?如何为这个特定的 ActiveRecord 类编写单元测试?
【发布时间】:2014-01-31 21:58:51
【问题描述】:

我想在Rspec 中为班级编写单元测试:

class Item < ActiveRecord::Base
  has_many :cart_items
  has_many :carts, through: :cart_items

  validates :price, presence: true
  validates :name, presence: true
end

我不确定我应该在这里测试什么...你能给出一些提示吗?

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing activerecord rspec


    【解决方案1】:

    使用shoulda-matchers gem,你可以做到这一点

    describe Item do
      it {should validate_presence_of :price}
      it {should validate_presence_of :name}
      it {should have_many(:cart_items)}
      it {should have_many(:carts).through(:cart_items)}
    end
    

    【讨论】:

      【解决方案2】:

      您可以在spec/models/item_spec.rb 中编写单元测试。

      我只是给你一个例子,你应该在你的规范中为这个特定的模型写什么

      require 'spec_helper'
      describe Task do
         before do
            @task = Task.new(name: "Example1", price:123)
         end 
         subject { @task }
      
         it { should respond_to(:name) } 
         it { should respond_to(:price) }  
         it { should respond_to(:cart_items) }   
         it { should be_valid }
      
         describe "when name is not present" do
            before { @task.name = " " }
               it { should_not be_valid } 
         end 
      end
      

      您可以根据验证、要求、字段、关联等编写更多内容

      【讨论】:

        猜你喜欢
        • 2022-12-21
        • 1970-01-01
        • 1970-01-01
        • 2018-03-13
        • 2022-01-11
        • 1970-01-01
        • 2019-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多