Testing "accepts_nested_attributes_for" with unit testing using Rspec

I am new to rails and testing models. My model class is as follows:

class Tester < Person has_one :company accepts_nested_attributes_for :skill end 

And I want to do a test for "accepts_nested_attributes_for: skill" with rspec without any other gem. How can i do this?

+4
source share
1 answer

For testing accepts_nested_attributes_for there are convenient shoulda sockets for creating gems, but you mentioned that you do not want to use other gems. Thus, using only Rspec, the idea is to set an hash of attributes that will include the required Tester attributes and a nested hash called skill_attributes that will include the required Skill attributes; then pass it to the create method of the Tester and see if it changes the number of Testers and the number of Skills . Something like that:

 class Tester < Person has_one :company accepts_nested_attributes_for :skill # lets say tester only has name required; # don't forget to add :skill to attr_accessible attr_accessible :name, :skill ....................... end 

Your tests:

  # spec/models/tester_spec.rb ...... describe "creating Tester with valid attributes and nested Skill attributes" do before(:each) do # let say skill has languages and experience attributes required # you can also get attributes differently, eg factory @attrs = {name: "Tester Testov", skill_attributes: {languages: "Ruby, Python", experience: "3 years"}} end it "should change the number of Testers by 1" do lambda do Tester.create(@attrs) end.should change(Tester, :count).by(1) end it "should change the number of Skills by 1" do lambda do Tester.create(@attrs) end.should change(Skills, :count).by(1) end end 

Hash syntax may vary. Also, if you have any uniqueness checks, make sure you generate dynamic @attrs dynamically before each test. Hi helper.

+6
source

Source: https://habr.com/ru/post/1395405/


All Articles