在Rails 3中,使用Rspec测试accepts_nested_attributes_for
关联的方法如下:
rspec-rails
和factory_girl_rails
等相关gem。FactoryGirl.define do
factory :user do
name "John Doe"
email "john@example.com"
end
factory :post do
title "My Post"
content "This is my post content."
association :user
end
factory :comment do
content "This is my comment."
association :post
end
endrequire 'rails_helper'
RSpec.describe Post, type: :model do
it "should accept nested attributes for comments" do
post = FactoryGirl.create(:post)
comment_attributes = FactoryGirl.attributes_for(:comment)
post.comments_attributes = [comment_attributes]
expect(post.comments.size).to eq(1)
expect(post.comments.first.content).to eq(comment_attributes[:content])
end
endspec/factories.rb
文件中定义相关的工厂对象,例如:spec/models/post_spec.rb
文件中编写测试代码,例如:rspec spec/models/post_spec.rb
命令,查看测试结果。以上是一个简单的示例,实际应用中可能需要根据具体需求进行更复杂的测试。
领取专属 10元无门槛券
手把手带您无忧上云