使用Rspec在模型中测试关系和方法

我正在研究rails项目和我在rails上的新function,我想使用rspec在模型中测试我的模型关系和方法。 我怎么能这样做我的模型关系是这样的

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 

我的idea_spec.rb文件是

 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 

如果您使用shoulda-matchers(https://github.com/thoughtbot/shoulda-matchers)gem,您可以将它们写为it{should belong_to(:person)}

但说实话,我没有从这些类型的测试中得到很多,AR经过了很好的测试。

简单的答案是,你没有。 你也没有测试has_manybelongs_to 。 这些规范/测试的位置在Rails代码库中,而不在您的代码库中。 你Idea规范绝对没有Rails没有。

以下是官方测试:

  1. belongs_to
  2. has_many

编辑:请阅读@ DavidChelimsky上面的评论。