我已 pastied 我为柱/ show.html.erb视图书面规格一个应用程序,我写的学习RSpec的一种手段。我仍然在学习嘲笑和存根。这个问题是具体到“应当列出所有相关评论”规范。

我要的是测试显示视图显示这篇文章的评论。但是,我不知道的是如何建立这个测试,然后有测试遍历与应包含(“XYZ”)语句。任何提示?其他建议还赞赏!感谢。

---修改

一些更多的信息。我已经应用到的意见,我认为一个named_scope(我知道,我这样做有点倒退在这种情况下),所以@ post.comments.approved_is(真)。 pastied代码与错误“为#未定义的方法`approved_is'”,这是有道理的,因为我告诉它存根意见,并返回注释响应。我真不知道,但是,如何串连存根,以便@ post.comments.approved_is(真)将返回注释的数组。

有帮助吗?

解决方案

成株真的是去这里的路。

在我的意见,在控制器和视图规格所有对象都应该与模拟对象存根。有没有真正需要花时间冗余测试应该已经在你的模型规格进行彻底的测试逻辑。

下面是如何我会成立在Pastie规格的例子...

describe "posts/show.html.erb" do

  before(:each) do
    assigns[:post] = mock_post
    assigns[:comment] = mock_comment
    mock_post.stub!(:comments).and_return([mock_comment])
  end

  it "should display the title of the requested post" do
    render "posts/show.html.erb"
    response.should contain("This is my title")
  end

  # ...

protected

  def mock_post
    @mock_post ||= mock_model(Post, {
      :title => "This is my title",
      :body => "This is my body",
      :comments => [mock_comment]
      # etc...
    })
  end

  def mock_comment
    @mock_comment ||= mock_model(Comment)
  end

  def mock_new_comment
    @mock_new_comment ||= mock_model(Comment, :null_object => true).as_new_record
  end

end

其他提示

我不知道这是否是最好的解决办法,但我设法让该规范由磕碰只是named_scope通过。我理解为一个更好的解决方案在此的任何反馈以及建议,给定有一个。

  it "should list all related comments" do
@post.stub!(:approved_is).and_return([Factory(:comment, {:body => 'Comment #1', :post_id => @post.id}), 
                                      Factory(:comment, {:body => 'Comment #2', :post_id => @post.id})])
render "posts/show.html.erb"
response.should contain("Joe User says")
response.should contain("Comment #1")
response.should contain("Comment #2")

它读取一个位讨厌。

您可以这样做:

it "shows only approved comments" do
  comments << (1..3).map { Factory.create(:comment, :approved => true) }
  pending_comment = Factory.create(:comment, :approved => false)
  comments << pending_comments
  @post.approved.should_not include(pending_comment)
  @post.approved.length.should == 3
end

或者其他类似的效果。 SPEC的行为,应批准返回批准后评论一些方法。这可能是一个简单的方法或named_scope。而未决会做一些明显的为好。

您也可以有一个工厂:pending_comment,是这样的:

Factory.define :pending_comment, :parent => :comment do |p|
  p.approved = false
end

或者,如果错误是默认的,你可以做同样的事情:approved_comments

我真的很喜欢尼克的做法。我有同样的问题我自己,我能够做到以下几点。我相信mock_model会正常工作。

post = stub_model(Post)
assigns[:post] = post
post.stub!(:comments).and_return([stub_model(Comment)])
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top