Rspec无法与mongoid创建关联模型

时间:2013-10-05 11:23:48

标签: ruby-on-rails rspec mongoid

我有两种模式:

文章模型

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不能为文章创建任何注释。我会感激任何建议。

1 个答案:

答案 0 :(得分:0)

在您访问该网页后,您似乎正在创建评论。 RSpec中的before块在外部第一顺序执行。

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