문제

나는 입술 내가 rspec을 배우는 수단으로 작성하는 응용 프로그램에서 게시물/show.html.erb보기에 대해 작성한 사양. 나는 여전히 모의와 스터브에 대해 배우고 있습니다. 이 질문은 "모든 관련 주석을 나열해야한다"사양에 따라 다릅니다.

내가 원하는 것은 Show View가 게시물의 의견을 표시한다는 것을 테스트하는 것입니다. 그러나 내가 확실하지 않은 것은이 테스트를 설정 한 다음 테스트를 반복하여 ( 'xyz') 문을 포함하는 것입니다. 힌트가 있습니까? 다른 제안도 감사합니다! 감사.

---편집하다

더 많은 정보. 나는 내 견해에 주석에 named_scope가 적용되어 있습니다 (이 경우이 경우 이것을 조금 뒤로 했음). @post.comments.ackroved_is (true). 코드 Jastied는 "정의되지 않은 메소드`approved_is ' # #"오류로 응답합니다. 이는 Stub 댓글을 말하고 주석을 반환 한 이후에 의미가 있습니다. 그러나 여전히 스텁 스를 체인하여 @post.comments.ackroved_is (true)가 댓글 배열을 반환 할 수있는 방법은 확실하지 않습니다.

도움이 되었습니까?

해결책

Stubbing은 정말로 여기로가는 길입니다.

제 생각에는 컨트롤러 및 뷰 사양의 모든 객체는 모의 객체로 스터브해야합니다. 모델 사양에서 이미 철저히 테스트 해야하는 논리를 중복 테스트하는 데 시간을 소비 할 필요가 없습니다.

다음은 내가 당신의 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

다른 팁

이것이 최상의 솔루션인지 확실하지 않지만, 이름이 지정된 _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

또는 그 효과에 무언가. 사양 동작, 승인 된 일부 방법은 게시물에 대한 승인 된 의견을 반환해야합니다. 그것은 평범한 방법이거나 명명 된 _scope 일 수 있습니다. 그리고 보류중인 것은 분명한 일도 할 것입니다.

다음과 같은 공장을 가질 수도 있습니다.

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

또는 false가 기본값 인 경우 : Approved_Comments에 대해 동일한 작업을 수행 할 수 있습니다.

나는 Nick의 접근 방식을 정말 좋아합니다. 나는 같은 문제가 있었고 다음을 할 수있었습니다. 나는 mock_model도 효과가 있다고 생각합니다.

post = stub_model(Post)
assigns[:post] = post
post.stub!(:comments).and_return([stub_model(Comment)])
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top