【问题标题】:Writing RSpec tests using MongoMapper使用 MongoMapper 编写 RSpec 测试
【发布时间】:2025-12-04 18:35:02
【问题描述】:

这是我在控制器中的测试:

describe "GET index" do
  it "assigns all comments as @comments" do
    comment = Comment.create! valid_attributes
    get :index, { :url => "http://localhost:3000", :use_route => :good_comments}
    assigns(:comments).should eq([comment])
  end
end

当我运行测试时,:commentscomment 的值不同。第一个是人们所期望的:

#<MyComments::Comment _id: BSON::ObjectId('4f0f7c41516d9f5a4a000001'), comment: "Some comment", created_at: Fri, 13 Jan 2012 00:35:13 UTC +00:00, images: [], resource_hash: "aHR0cDovL2xvY2FsaG9zdDozMDAwLw==", updated_at: Fri, 13 Jan 2012 00:35:13 UTC +00:00, urls: [], user_id: nil>

第二个很奇怪:

#<Plucky::Query sort: [["created_at", -1]], transformer: #<Proc:0x007fe86e3184c8@/Users/shamoon/.rvm/gems/ruby-1.9.2-p290@global/gems/mongo_mapper-0.10.1/lib/mongo_mapper/plugins/querying.rb:79 (lambda)>

我不确定发生了什么,因此我们将不胜感激。

谢谢 =)

编辑:添加控制器代码

# POST /comments
# POST /comments.json
def create
  @comment = Comment.new params[:comment]
  respond_to do |format|
    if @comment.save
      format.html { redirect_to :back, notice: 'Comment was successfully created.' }
      format.json { render json: @comment, status: :created, location: @comment }
    else
      format.html { render action: "new" }
      format.json { render json: @comment.errors, status: :unprocessable_entity }
    end
  end
end

# GET /comments
# GET /comments.json
def index
  url = ""
  if params[:url]
    url = params[:url]
  end
  resource_hash = Comment.encode_url url

  @newComment = Comment.new
  @newComment.resource_hash = resource_hash

  @comments = Comment.find_all_by_resource_hash resource_hash
  @comments = Comment.sort(:created_at.desc)

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @comments }
  end
end

编辑:更新索引操作

def index
  url = ""
  if params[:url]
    url = params[:url]
  end
  resource_hash = Comment.encode_url url

  @newComment = Comment.new
  @newComment.resource_hash = resource_hash

  @comments = Comment.where(:resource_hash => resource_hash).sort(:created_at.desc)

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @comments }
  end
end

【问题讨论】:

  • 请同时发布控制器代码,用于create 操作以及任何相关的前后过滤器。
  • 糟糕,我的意思是索引操作!对此感到抱歉

标签: ruby-on-rails-3 mongomapper rspec-rails


【解决方案1】:
@comments = Comment.find_all_by_resource_hash resource_hash
@comments = Comment.sort(:created_at.desc)

那是你的问题,你正在覆盖第二行中的 @cmets 变量,先试试这个,我不确定它是否会让你调用 sort ,但请看:

@comments = Comment.find_all_by_resource_hash resource_hash
@comments = @comments.sort(:created_at.desc)

更新

尝试这样做:

@comments = Comment.where(:resource_hash => resource_hash).sort(:created_at.desc).all

【讨论】:

  • 更新了索引操作(参见上面的代码)。仍然没有通过测试
  • 我认为问题在于 RSpec 没有访问我的数据库。我如何告诉它我的数据库参数?
  • 应该在你的test环境中设置。