Nested Model Form と RSpec

RSpec で Nested Model Form を含むビューのテストを書く方法のメモ。


require 'spec_helper'

class Question; end
class Choice; end

describe "questions/new" do
before(:each) do
@question = mock_model(Question).as_null_object.as_new_record
@choices = []
10.times do
@choices << mock_model(Choice).as_null_object.as_new_record
end
@question.stub(:choices).and_return(@choices)
@question.stub(:respond_to?).
with('choices_attributes=').and_return(true)

assigns[:question] = @question
render 'questions/new'
end

it "should display a nested model form" do
response.should have_selector('form') do |form|
0.upto(9).each do |i|
form.should have_selector('input', :type => 'text',
:name => "question[choices_attributes][#{i}][sentence]")
end
end
end
end

赤字で強調した部分がポイントです。

ActiveRecord::Base.accepts_nested_attributes_for をエミュレートしています。

  • -

P.S.

この方法はダメ。:respond_to? を stub してしまうと弊害が多い。


@question.stub(:choices_attributes=).and_return(true)

普通にこんな風に書けばよかった。