0

组合一个简单的文章用户关联,其中用户是文章的作者

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

相关的规范是 require '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 => '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)>'

关于如何解决这个问题的任何建议?谢谢!!

4

1 回答 1

0

您使用的“描述...做”层次结构不正确。before do应该包裹在describe ...do. 例如

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
于 2012-04-17T04:09:48.437 回答