我有一个 rails 控制器的规范,用于测试关联模型的创建:
楷模:
class Foo < ActiveRecord::Base
has_many :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
attr_accessible :foo, :foo_id
end
控制器规格:
@foo = FactoryGirl.create(:foo)
expect {
post :create, { bar: FactoryGirl.attributes_for(:bar, foo_id: @foo.id )}
}.to change(Bar, :count).by(1)
如果我将此规范更改为不必进行foo_id
批量分配的形式,它将中断ActiveRecord::AssociationTypeMismatch expected Foo got String
:
@foo = FactoryGirl.create(:foo)
expect {
post :create, { bar: FactoryGirl.attributes_for(:bar, foo: @foo )}
}.to change(Bar, :count).by(1)
和
describe Bar do
it { should_not allow_mass_assignment_of(:foo_id) }
end
控制器代码非常简单:
def create
@bar = Bar.new(params[:bar])
if @bar.save
redirect_to @bar
else
render action: 'new'
end
end
有没有办法让规范在不foo_id
访问的情况下运行?