ruby-on-rails 如何从RSpec中删除重复

roqulrg3  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(135)

下面是我的spec文件:

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

字符串
如何避免在上述两种情况下重复下面的代码块?

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

sd2nnvve

sd2nnvve1#

如果你真的想结束一些测试,你可以这样做:

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

字符串
正如您所看到的,当您想要在一个方法中 Package 多个测试时,这真的很方便。

nuypyhwy

nuypyhwy2#

你的规范描述了你期望从你的代码中得到的行为--这种重复是可以的。
如果它失控了,使用不同的上下文来隔离不同的期望。例如,你可以将这些重复的期望分解到一个新的上下文中,这个上下文只测试页面,而不管答案是什么。

相关问题