Ruby on rails 我应该为模型编写什么样的RSpec测试?
我对Rails和测试完全陌生,我写了这个模型:Ruby on rails 我应该为模型编写什么样的RSpec测试?,ruby-on-rails,ruby-on-rails-3.2,rspec-rails,Ruby On Rails,Ruby On Rails 3.2,Rspec Rails,我对Rails和测试完全陌生,我写了这个模型: class KeyPerformanceInd < ActiveRecord::Base #attr_accessible :name, :organization_id, :target include ActiveModel::ForbiddenAttributesProtection belongs_to :organization has_many :key_performance_intervals, :for
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
在这种情况下,您不需要做更多的工作,还可以使用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
查看以获得更多信息。谢谢,这里有两个宝石,一个是名字shoulda,另一个是shoula matchers,我需要包括“两者”吗?或者shoulda mathers将在内部自动使用shoulda?shoulda matchers是shoulda的一个依赖项,但您可以简单地包括shoulda matchers。将文件放入组测试中。
it "should be valid with valid attributes" do
user = FactoryGirl.create(:user)
user.should be_valid
end