1

我有两个模型:

文章模型

class Article
 include Mongoid::Document
 include Mongoid::Timestamps

 field :title, type: String
 field :body, type: String
 default_scope queryable.order_by(:created_at.desc)

 scope :archive, -> { where(:created_at.lte => Time.now - 1.month)}

 embeds_many :comments, as: :commentable
 validates_presence_of :title, :body
end

和评论模型

class Comment
  include Mongoid::Document
  include Mongoid::Timestamps

  embedded_in :commentable, polymorphic: true
  embeds_many :answers, as: :commentable, class_name: "Comment"

  default_scope queryable.order_by(:created_at.asc)

  field :body, type: String
  validates_presence_of :body
end

我的测试:

describe "Article#show" do
 let!(:article) {FactoryGirl.create(:article)}

 before{visit article_path(article)}
 subject{ page }

 describe "can be commented by other user" do
   before do
     @comment1 = article.comments.create(body: Faker::Lorem.paragraph)
     @comment2 = article.comments.create(body: Faker::Lorem.paragraph)
     @comment3 = article.comments.create(body: Faker::Lorem.paragraph)
   end

  it {should have_selector("div.comment_text", text: @comment1.body)}
  it {should have_selector("div.comment_text", text: @comment2.body)}
  it do
      #save_and_open_page
      should have_selector("div.comment_text", text: @comment3.body)}
    end
 end

错误:

Failure/Error: it {should have_selector("div .comment_text", text: @comment1.body)}
 Capybara::ExpectationNotMet:
   expected to find css "div .comment_text" with text "Aliquam omnis et ullam quae
   maiores voluptates. Rerum dicta dolores alias voluptates rerum voluptas autem.
   Nemo non quia possimus. Nam commodi odio quia et. Aut non odit ratione quas sit accusantium ut." but there were no matches

鉴于我有部分:

=render "shared/comments", model: @article

部分(从 consol 创建评论时显示正确的结果):

    .comments
    -model.comments.each do |comment|
      .comment
        = image_tag("delete/brian.jpg", class: "avatar")
        .comment-author
          =Faker::Name.name
          %time.comment-date= l(comment.created_at)
        .comment-text
          = comment.body
        -if comment.answers.any?
          -comment.answers.each do |answer|
            .comments-answers
              =image_tag('delete/brian.jpg',class: "avatar")
              .comment-author
                =Faker::Name.name
                %time.comment-date= l(comment.created_at)
              .comment-text= answer.body

我可以使用“Article.first.comments.create”从 consol 创建评论并在浏览器中查看,但是当我测试它时,RSpec 无法为文章创建任何评论。我会很感激任何建议。

4

1 回答 1

0

看起来您在访问该页面后正在创建评论。beforeRSpec 中的块以外部第一顺序执行。

尝试将visit article_path(article)台阶移动到内部before块中。

于 2013-10-05T17:23:55.863 回答