Rspec测试失败:创建新记录而不是使用现有记录

时间:2013-07-01 12:06:33

标签: ruby-on-rails rspec ruby-on-rails-3.2 rspec-rails

我有以下代码:

describe "when visiting roll call with no notes" do
  before do
    login_as_sensei
    @dojo = FactoryGirl.create(:dojo, name: "Melbourne")
    @time = FactoryGirl.create(:times, dojo: @dojo)
    @roll = FactoryGirl.create(:roll_call)
    visit time_roll_calls_path("melbourne", "14-2-2013", "1000")
  end

  specify { @roll.notes.should be_blank }
  it { should_not have_content("This is a note!") }

  describe "and filling in note information correctly" do
    before do
      fill_in "roll_call[notes]", with: "This is a note!"
      click_button "Add Notes"
    end

    it { should have_content("This is a note!") } # 'it' refers to the page
    specify { RollCall.last.notes.should_not be_blank }
    specify { @roll.notes.should_not be_blank }
    specify { @roll.reload.notes.should_not be_blank }
  end
end

据我所知,最后的4个测试都应该通过,但只有前2个测试通过:

it { should have_content("This is a note!") }
specify { RollCall.last.notes.should_not be_blank }

最后2个返回以下错误:

1) RollCalls when visiting roll call with no notes and filling in note information correctly 
 Failure/Error: specify { @roll.notes.should_not be_blank }
   expected blank? to return false, got true
 # ./spec/features/roll_calls_spec.rb:241:in `block (4 levels) in <top (required)>'

2) RollCalls when visiting roll call with no notes and filling in note information correctly 
 Failure/Error: specify { @roll.reload.notes.should_not be_blank }
   expected blank? to return false, got true
 # ./spec/features/roll_calls_spec.rb:242:in `block (4 levels) in <top (required)>'

这是rspec应该如何工作还是我做错了什么?

1 个答案:

答案 0 :(得分:1)

您在此处混合验收规格和请求规格。当您执行资金请求时(通过fill_in等),将不会修改@roll

验收规范测试响应的内容。请求针对给定请求的记录的规范测试操作。您可以考虑将测试拆分为:

# Acceptance test
describe "when visiting roll call with no notes" do
  before do
    login_as_sensei
    @dojo = FactoryGirl.create(:dojo, name: "Melbourne")
    @time = FactoryGirl.create(:times, dojo: @dojo)
    @roll = FactoryGirl.create(:roll_call)
    visit time_roll_calls_path("melbourne", "14-2-2013", "1000")
  end

  it { should_not have_content("This is a note!") }

  describe "and filling in note information correctly" do
    before do
      fill_in "roll_call[notes]", with: "This is a note!"
      click_button "Add Notes"
    end

    it { should have_content("This is a note!") } # 'it' refers to the page
  end
end

# Request specs
describe RollCallsController do
  describe "#action" do
    before do
      login_as_sensei
      @roll = FactoryGirl.create(:roll_call)

    end

    it "should initially be blank" do
      get "/some/path", :id => @roll.id
    end

    it "should add a note" do
      post "/roll_calls/#{@roll.id}/notes/add", roll_call: {notes: "New note"}
      @roll.reload.notes.should_not be_blank
      @roll.reload.notes[0].note.should == "New note"
    end
  end
end