ruby on rails 测试笔记(model)
rake db:migrate RAILS_ENV=test
1.App/modles/test_paper.rb
class TestPaper < ActiveRecord::Base
attr_accessible :course_id, :user_id
belongs_to :course
belongs_to :user
has_many :test_paper_test_questions
has_many :test_questions, :through => :test_paper_test_questions
validates :course_id, :presence => true
validates :user_id, :presence => true
def self.make_test_paper_for(course,user)
paper = self.create(:course_id => course.id,:user_id => user.id)
paper.select_questions!
paper
end
def select_questions!
if self.test_questions.blank?
test_questions = self.course.test_questions.to_a.shuffle
selected = test_questions[0,10]
self.test_questions = selected
end
end
def self.find_paper_for(course,user)
course.test_papers.find_by_user_id(user.id)
end
end
2.spec/factories/
--test_paper.rb
FactoryGirl.define do
factory :test_paper do
course
user
end
end
--course.rb
FactoryGirl.define do
factory :course do
sequence(:name){|n| "course_name_#{n}" }
sequence(:cid){|n| n }
sequence(:desc){|n| "desc_#{n}" }
sequence(:syllabus){|n| "syllabus_#{n}" }
creator
end
end
3.spec/models/test_paper_spec.rb
第一种:
require 'spec_helper.rb'
describe TestPaper do
describe '.make_test_paper_for' do
let(:course) {FactoryGirl.create(:course)}
let(:user) {FactoryGirl.create(:user)}
let(:paper) {FactoryGirl.create(course, user)}
before{
1.upto(20){FactoryGirl.create(:test_question, :course => course)}
}
it '创建一个新试卷并随机选出10道题组卷' do
paper.user.should eq user
paper.course.should eq course
paper.test_questions.count.should eq 10
end
end
end
第二种:
require 'spec_helper.rb'
describe TestPaper do
describe '.make_test_paper_for' do
before{
@course = FactoryGirl.create(:course)
@user = FactoryGirl.create(:user)
1.upto(20){FactoryGirl.create(:test_question, :course => @course)}
@paper = FactoryGirl.create(@course,@ user)}
}
it '创建一个新试卷并随机选出10道题组卷' do
@paper.user.should eq @user
@paper.course.should eq @course
@paper.test_questions.count.should eq 10
end
end
end
第三种:
require 'spec_helper.rb'
describe TestPaper do
describe '.make_test_paper_for' do
let(:course) {FactoryGirl.create(:course)}
let(:user) {FactoryGirl.create(:user)}
let(:paper) {FactoryGirl.create(course, user)}
subject {TestPaper.make_test_paper_for(course, user)}
before{
1.upto(20){FactoryGirl.create(:test_question, :course => course)}
}
it '创建一个新试卷并随机选出10道题组卷' do
paper.user.should eq user
paper.course.should eq course
paper.test_questions.count.should eq 10
end
context '创建一个新试卷' do
its(:user) {should eq user}
its(:course) {should eq course}
it '随机选10道题组卷' do
subject.test_questions.count.should eq 10
end
end
end
end
4.rspec spec/models/test_paper_spec.rb