开发者

How to remove duplication from RSpec

context "answer is correct" do

before(:each) do
  @answer = stub_model(Answer, :correct => true).as_new_record
  assigns[:answer] = @answer

  render "answers/summarize"
end

it "should display flashcard context properly" do
  response.should contain("Quiz")
end

it "should summarize results" do
  response.should contain("is correct")
end

end

context "answer is incorrect" do

before(:each) do
  @answer = stub_model(Answer, :correct => false).as_new_record
  assigns[:answer] = @answer

  render "answers/summarize"
end

it "should display flashcard context properly" do
  response.should contain("Quiz")
end

it "should summarize results" do
  response.should contain("is incorrect")
end

end

How do I avoid repeating the fo开发者_Go百科llowing block within both of the above contexts?

it "should display flashcard context properly" do

  response.should contain("Quiz")

end


Your specs describe the behavior you expect from your code - this amount of repetition is ok.

If it gets out of hand, use different contexts to isolate different expectations. For example, you could factor those duplicate expectations into a new context that just tests the page no matter what the Answer is.


If you really want to wrap up some of your tests, you can do it like this:

def answer_tests
  it "should display flashcard context properly" do
    response.should contain "Quiz"
  end

  it "should do be awesome" do
    response.should be_awesome
  end
end

context "answer is correct" do
  answer_tests

  it "should summarize results" do
    response.should contain "is correct"
  end
end

context "answer is incorrect" do
  answer_tests

  it "should summarize results" do
    response.should contain "is incorrect"
  end
end

As you can see, this is really handy when you have more than one test you want to wrap up in a method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜