test

用 rspec 替代 Test::Unit 做测试

用 simplecov 看代码覆盖率。

用 shoulda 测试 scope 和 validates

用 factory_girl_rails 替代夹具

用 capybara

用 database_cleaner

===

用 belong_to 测试 associations 和
it { Factory.create(:了,

                  :belongs_to => Factory(:实际),
                  :project => Factory.create(:project)).should be_valid }

用 validate_xxxx_of 测试 validates

用 respond_to 测试 delegate

用 类.respond_to 和 rails c 测试 scope

  describe "Methods" do
    it { should respond_to :projects }
  end

测试部分(不带参数)方法

#projects that has this key
  def projects ##
    if is_deploy_key
      [project]
    else
      user.projects
    end
  end

describe "Scopes" do
    it "should have a today named scope that returns ..." do
      Note.today.where_values.should == ["created_at >= '#{Date.today}'"]
    end
  end

测试

scope :today, where("created_at >= :date", :date => Date.today) ##

对 ‘一个’ 测试方法 创建局部变量 可直接用 类名 + ???

而 实例变量 则用 Factory (对其 belongs_to 的还要自己给出 !)
当是 ‘多个’ 测试方法时,还应该用 let , 如

let(:project) { Factory :project }

有时可以用 before 重构 没少代码量
before do

end

  describe '#to_s' do
    it "should return title" do
      job.to_s.should eql job.title
    end
  end

  describe '#contracts' do
    subject { job.contracts }
    it { should be_an_instance_of(Array) }
    it { should eql [:cdi]}
  end

  describe '#generate_token' do
    after(:each) do
      job.generate_token
    end
    it "should update #token" do
      job.should_receive(:update_attribute).with(:token, kind_of(String))
    end
    it "should use SecureRandom.hex" do
      SecureRandom.should_receive(:hex).with(13).once()
    end
  end

  describe '#validate_contracts' do
    it "should add an error if there is contracts" do
      job.cdi = false
      job.valid?
      job.errors.messages.should have_key :contracts_error
    end
  end

测试

  def to_s; title end

  def contracts
    {cdi: cdi, cdd: cdd, freelance: freelance, internship: internship}.delete_if {|k,v| !v}.keys
  end

  def generate_token
    update_attribute(:token, SecureRandom.hex(13))
  end

  private
  def validate_contracts
    errors.add(:contracts_error, "Selectionner au moins un type de contrat") unless (cdd or cdi or freelance or internship)
  end

对于 访问器

attr_accessor :freelance, :cdi, :cdd, :internship, :remote

也同样可以用 respond_to 来测试

  it { should respond_to(:freelance)}
  it { should respond_to(:cdi)}
  it { should respond_to(:cdd)}
  it { should respond_to(:internship)}
  it { should respond_to(:remote)}

你可能感兴趣的:(test)