: O. Yuanying

RSpec on Rails で ActiveRecord::RecordInvalid のテスト

RSpec on Rails を使って仕様を書いてるときに、コントローラ中で ActiveRecord::RecordInvalid が発生する仕様を書こうとしたのだけどうまくいかない。


  it '妥当でない値が Post された場合、new ページが再びレンダリングされる。' do
    @fa.stub!(:save!).and_raise(ActiveRecord::RecordInvalid)
    @fa.should_receive(:save!).and_raise(ActiveRecord::RecordInvalid)
    
    ...
  end

こんな感じに書くとテスト中に以下のようなエラーがでる。


  Mock 'errors' received unexpected message :full_messages with (no args)
  ./spec/controllers/admin_controller_spec.rb:58:in `new'
  ./spec/controllers/admin_controller_spec.rb:58:
  script/spec:4:

これは before 中に以下のように書けばおk。


  before(:each) do
    @fa = mock_model(TestObject)
    @fa.errors.stub!(:full_messages).and_return([])
  end
  
  it '妥当でない値が Post された場合、new ページが再びレンダリングされる。' do
    error = ActiveRecord::RecordInvalid.new(@fa)
    @fa.stub!(:save!).and_raise(error)
    @fa.should_receive(:save!).and_raise(error)

どうやら、@fa.errors.stub!(:full_messages).and_return([]) が重要らしい。

参考