在简单的文章 - 用户关联中,“无法定义单例”错误

时间:2012-04-17 04:00:19

标签: ruby-on-rails

将用户为文章作者的简单文章 - 用户关联放在一起

class Article < ActiveRecord::Base
  attr_accessor :id, :name, :title, :title_image, :keywords, :related_urls, :content, :meldd
  validates_presence_of :title, :name, :title_image, :keywords, :related_urls, :content
  as_enum :status, [:new, :draft, :private, :published], :column => "article_status", :prefix => true
  validates_as_enum :status
  belongs_to :author, :class_name => 'User'

end



class User < ActiveRecord::Base
  validates_format_of :pen_name, :with => /\A[[:word]]+\Z/
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

  has_many :articles, :foreign_key => 'author_id'

  easy_roles :roles
end

相关规格是     需要'spec_helper'     require_relative'../ support / cells / articles / recent_updates_data'

describe Article do
  include ArticlesCellSpecHelpers

  before(:each) do
    @it = stub_model Article
  end

  describe "basic, existential structure" do
    it "starts with blank attributes" do
      @it.name.should be_nil
      @it.title.should be_nil
      @it.title_image.should be_nil
      @it.keywords.should be_nil
      @it.related_urls.should be_nil
      @it.content.should be_nil
    end

    it "is an ActiveRecord subclass" do
      @it.should be_a ActiveRecord::Base
    end

  describe "associations" do
    it "has an author" do
      author = stub_model User, :pen_name => 'Joe Blow', :email => 'joe.blow@example.com'
      params = recent_updates_data.first()
      params[:author_id] = author.id
      params[:status] = :published
      article = stub_model Article, params
      article.author_id.should == author.id
    end
  end

这很奇怪,但是如果你注释掉“belongs_to:author,:class_name =&gt;'User'”那么所有的测试都没问题,但是如果那行是,那么就会抛出以下错误:

Article basic, existential structure is an ActiveRecord subclass
     Failure/Error: @it = stub_model Article
     TypeError:
       can't define singleton
     # ./spec/models/article_spec.rb:9:in `block (2 levels) in <top (required)>'

有关如何解决此问题的任何建议?谢谢!

1 个答案:

答案 0 :(得分:0)

您正在使用的“describe ... do”层次结构不正确。 before do应该包含在describe ...do中。 e.g。

describe "basic, existential structure" do

  # put this before block into the describe block
  before(:each) do
    @it = stub_model Article
  end

  it "starts with blank attributes" do
  end
end