Testing the relationships and Methods In Model using Rspec

混江龙づ霸主 提交于 2019-12-10 15:54:34

问题


I m working on rails project and i m new on rails and I want to test my model relationships and methods in model using rspec. How could I do this my model relationships are like this

class Idea < ActiveRecord::Base

  belongs_to :person
  belongs_to :company
  has_many :votes
  validates_presence_of :title, :description
  def published?
    if self.status == "published"
      return true
    else
      return false
    end
  end

  def image_present
    if self.image_url
      return self.image_url
    else
      return "/images/image_not_found.jpg"
    end
  end



  def voted
    self.votes.present?
  end
end

My idea_spec.rb file is

require 'spec_helper'

describe Idea do

  it "should have title" do
  Idea.new(:title=>'hello',:description=>'some_desc').should be_valid
  end

  it "should have description" do
  Idea.new(:title=>'hello',:description=>'some_desc').should be_valid
  end
end

回答1:


If you use shoulda-matchers (https://github.com/thoughtbot/shoulda-matchers) gem you can write these as it{should belong_to(:person)}

But to be honest I don't get a lot out of these types of test, AR is well tested.




回答2:


Simple answer is, you do not. Neither do you test has_many or belongs_to. The place for these specs / tests is in Rails codebase, and not in your codebase. You Idea spec gives you absolutely nothing that Rails does not.

Here are the official tests:

  1. belongs_to
  2. has_many

Edit: Please read @DavidChelimsky's comment above.



来源:https://stackoverflow.com/questions/9175150/testing-the-relationships-and-methods-in-model-using-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!