首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何使用Rspec Rails3测试accepts_nested_attributes_for

在Rails 3中,使用Rspec测试accepts_nested_attributes_for关联的方法如下:

  1. 首先,确保已经安装了rspec-railsfactory_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 end
  2. spec/factories.rb文件中定义相关的工厂对象,例如:
  3. spec/models/post_spec.rb文件中编写测试代码,例如:
  4. 运行rspec spec/models/post_spec.rb命令,查看测试结果。

以上是一个简单的示例,实际应用中可能需要根据具体需求进行更复杂的测试。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券