gpt4 book ai didi

ruby-on-rails - 我应该为模型编写什么样的 RSpec 测试?

转载 作者:行者123 更新时间:2023-12-02 07:37:41 25 4
gpt4 key购买 nike

我对 Rails 和测试完全陌生,我编写了这个模型:

class KeyPerformanceInd < ActiveRecord::Base
#attr_accessible :name, :organization_id, :target

include ActiveModel::ForbiddenAttributesProtection

belongs_to :organization
has_many :key_performance_intervals, :foreign_key => 'kpi_id'

validates :name, presence: true
validates :target, presence: true
validates :organization_id, presence: true

end

我的问题是对于这样的模型,我应该编写哪些 RSpec 测试?像这样的东西?或者有萌事可做?我听说了 FactoryGirl,我需要它来测试这个模型还是用于测试 Controller 中的东西?

Describe KeyPerformanceInd do
it {should belong_to(:key_performance_interval)}
end

最佳答案

在这种情况下,你不需要做更多,你也可以使用shoulda-matchers gem 让你的代码真正干净:

it { should belong_to(:organization) }
it { should have_many(:key_performance_intervals) }

it { should validate_presence_of(:name) }
it { should validate_presence_of(:target) }
it { should validate_presence_of(:organization_id) }

就是这样。

在这种情况下,您不需要 FactoryGirl,它用于创建有效且可重用的对象。但是您可以在模型测试中使用工厂。一个简单的例子:

你的工厂:

FactoryGirl.define do
factory :user do
first_name "John"
last_name "Doe"
end
end

你的测试:

it "should be valid with valid attributes" do  
user = FactoryGirl.create(:user)
user.should be_valid
end

检查 Factory Girl documentation获取更多信息。

关于ruby-on-rails - 我应该为模型编写什么样的 RSpec 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14731860/

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