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



我有以下代码:

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应该这样工作吗?还是我做错了什么?

您在这里混合了接受规范和请求规范。当您执行水豚请求时(通过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

最新更新