RSpec-Rails (基礎篇)(5): 撰寫Model測試
建立另一個model與post產生關連。
$ rails g model comment content:text post_id:integer
$ rake db:migrate
在app/models/post.rb撰寫新的code。
class Post < ActiveRecord::Base
  validates :title, :presence => true
  has_many :comments
  def self.no_content
    where(:content => nil)
  end
  def abstract
    self.content[0..20]
  end
end
在app/models/comment.rb當中建立關連。
class Comment < ActiveRecord::Base
  belongs_to :post
end
接著在原本的model測試檔案內,新增測試。
spec/models/post_spec.rb
    it "validates title" do
      expect(Post.new).not_to be_valid
      expect(Post.new(:title => "title")).to be_valid
    end
    it ".no_content" do
    post_with_content = Post.create(:title => "title", :content => "content")
      post_without_content = Post.create(:title => "title", :content => nil)    
      expect(Post.no_content).to include post_without_content
      expect(Post.no_content).not_to include post_with_content
    end
    it "#abstract" do
      post = Post.create(:title => "title", :content => "12345678901234567890_not_abstract")
      expect(post.abstract).to include("12345678901234567890")
      expect(post.abstract).not_to include("not_abstract")
    end
    it "has_many comments" do
      post = Post.create(:title => "title", :content => "content")
      comment = Comment.create(:content => "content", :post_id => post.id)
      expect(post.comments).to include(comment)
    end
進行測試:
$ rspec spec/models
應該就會順利通過囉!

