首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在简单的文章-用户关联中出现"can't define“错误

在简单的文章-用户关联中出现"can't define“错误
EN

Stack Overflow用户
提问于 2012-04-17 12:00:19
回答 1查看 159关注 0票数 0

构建一个简单的文章-用户关联,其中用户是文章的作者

代码语言:javascript
运行
复制
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’

代码语言:javascript
运行
复制
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'“,那么所有的测试都是正常的,但是如果这一行在里面,那么就会抛出下面的错误:

代码语言:javascript
运行
复制
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)>'

对如何解决这个问题有什么建议吗?谢谢!!

EN

回答 1

Stack Overflow用户

发布于 2012-04-17 12:09:48

您使用的"describe ...do“层次结构不正确。应该将before do包装在describe ...do中。例如:

代码语言:javascript
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10184865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档