rspec rails nested_attributes on controller - ruby-on-rails

I am using Rspec to test a controller that received nested_attributes. A class Option can has_many Suboptions.
models/suboption.rb:
class Suboption < ApplicationRecord
belongs_to :option,
optional: true
validates :name, presence: true
end
models/option.rb:
class Option < ApplicationRecord
belongs_to :activity
has_many :suboptions, dependent: :destroy
accepts_nested_attributes_for :suboptions, allow_destroy: true,
reject_if: ->(attrs) { attrs['name'].blank? }
validates :name, presence: true
end
Params:
def option_params
params.require(:option).permit(:name, :activity_id, :students_ids => [], suboptions_attributes: [:id, :name, :_destroy])
end
spec/controller/options_controller_spec.rb:
describe "POST #create" do
let(:option) { assigns(:option) }
let(:child) { create(:suboption) }
context "when valid" do
before(:each) do
post :create, params: {
option: attributes_for(
:option, name: "opt", activity_id: test_activity.id,
suboptions_attributes: [child.attributes]
)
}
end
it "should redirect to options_path" do
expect(response).to redirect_to options_path
end
it "should save the correctly the suboption" do
expect(option.suboptions).to eq [child]
end
end
Testing Post, I would like to ensure that option.suboptions to be equal to [child]. But I don't know how to pass the attributes of the instance child to suboptions_attributes. This way that I did is not working.

Found the answer:
describe "POST #create" do
let(:option) { assigns(:option) }
context "when valid" do
before(:each) do
post :create, params: {
option: attributes_for(:option, name: "opt", activity_id: test_activity.id,
suboptions_attributes: [build(:option).attributes]
)
}
end
it "should save suboptions" do
expect(option.suboptions.first).to be_persisted
expect(Option.all).to include option.suboptions.first
end
it "should have saved the same activity_id for parent and children" do
expect(option.suboptions.first.activity_id).to eq option.activity_id
end
end
This is a way of doing it.

Related

Rails rspec — test a model method that depends on associations

I have a simple test to check a custom method on a model Beta::Group
class Beta::Group < ApplicationRecord
has_many :beta_testers, dependent: :destroy, class_name: 'Beta::Tester', foreign_key: 'beta_group_id'
has_many :users, through: :beta_testers, source: :user, class_name: '::User'
validates :name, presence: true, uniqueness: true
def get_beta_tester(user_id)
beta_testers.find_by({ user_id: user_id })
end
end
describe '#get_beta_tester' do
subject { create(:beta_tester, user: user, beta_group: new_group) }
let!(:user) { create(:user) }
let!(:new_group) { create(:beta_group) }
it 'should return the beta tester when given a user_id' do
tester = new_group.get_beta_tester(user.id)
expect(tester).to eq(subject)
end
end
But it fails, because tester is nil. Why is it nil?
EDIT - what I have tried
I tried this, which works, but I don't understand why this works and the previous did not. Can someone explain why?
describe '#get_beta_tester' do
it 'should return the beta tester when given a user_id' do
user = create(:user)
beta_group = create(:beta_group)
beta_tester = create(:beta_tester, user: user, beta_group: beta_group)
tester = beta_group.get_beta_tester(user.id)
expect(tester).to eq(beta_tester)
end
end
You execute the subject after the find_by, try the following
describe '#get_beta_tester' do
subject { create(:beta_tester, user: user, beta_group: new_group) }
let!(:user) { create(:user) }
let!(:new_group) { create(:beta_group) }
let(:tester) { new_group.get_beta_tester(user.id) }
it 'should return the beta tester when given a user_id' do
subject
expect(tester).to eq(subject)
end
end

Rails: How to Unit test for validations of nested attributes?

I have a the following has_many model associations in my app:
User < Company < Deed < Subtransaction,
where Deed accepts_nested_attributes_for :subtransactions. I wish to test my Model validations using Minitest and fixtures.
I have trouble, however, testing the nested attributes for validity. For example , If I clear all nested attributes using
#deed.subtransactions.clear I correctly get a test response that the model is not valid.
However
#deed.subtransactions.first.num_shares = " " does not seem to work.
How do I properly test these nested attributes for validity?
My test:
class DeedTest < ActiveSupport::TestCase
def setup
#user = users(:dagobert)
#newco = companies(:newco)
params = { :deed =>
{
:date => deeds(:inc_new).date,
:subtransactions_attributes =>
{ '1' =>
{
:shareholder_name => "Shareholder 1",
:num_shares => subtransactions(:new_subt1).num_shares
},
'2' =>
{
:shareholder_name => "Shareholder 2",
:num_shares => subtransactions(:new_subt2).num_shares
}
}
}
}
#deed = #newco.deeds.new(params[:deed])
end
# test: does not raise any error messages
test "num_shares should be present for a subtransaction" do
#deed.subtransactions.first.num_shares = nil
assert_not #deed.valid?
end
# test passing: The params are submitted correctly and pass validation
test "fixture values should be valid" do
assert #deed.valid?
end
# test passing: I can test the validity of deed attributes
test "date should be present" do
#deed.date = " "
assert_not #deed.valid?
end
# test passing: when I clear #deed.subtransactions the object is no longer valid
test "a subtransaction should be present" do
#deed.subtransactions.clear
assert_not #deed.valid?
end
end
UPDATE
Deed model:
class Deed < ActiveRecord::Base
belongs_to :company
has_many :subtransactions, dependent: :destroy
accepts_nested_attributes_for :subtransactions, allow_destroy: true,
reject_if: ->(a) { a['shareholder_name'].blank? && a['num_shares'].blank? }
validates_associated :subtransactions
validates :date, presence: true
validates :subtransactions, presence: true
end
Subtransaction model:
class Subtransaction < ActiveRecord::Base
belongs_to :deed
belongs_to :shareholder
validates :num_shares, presence: true, length: { maximum: 50 },
:numericality => { only_integer: true }
validates :shareholder_name, presence: true
# end class
end

Rails 4 - error creating associations through Fabricator in Rspec tests

Ok, i am trying to use Fabricator with my Rspec tests to mock some data for the tests. I'm having some trouble with a belongs_to association, however. Here's what i have so far:
user.rb
class User < ActiveRecord::Base
authenticates_with_sorcery!
belongs_to :organization
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates_presence_of :full_name
validates_presence_of :email
validates_uniqueness_of :email, on: :create
validates_format_of :email, with: VALID_EMAIL_REGEX, on: :create
validates_presence_of :password, on: :create
validates_confirmation_of :password
end
organization.rb
class Organization < ActiveRecord::Base
authenticates_with_sorcery!
has_many :users, dependent: :destroy
accepts_nested_attributes_for :users, :allow_destroy => true
validates_presence_of :name
end
integration_spec.rb
require 'rails_helper'
describe "Shopping Cart Requests" do
let!(:user) { Fabricate(:user) }
before(:each) do
login_user_post("admin#example.com", "password")
end
context "when I visit the shopping cart" do
it " show the logged in users' cart items " do
#Test stuff
end
end
end
user_fabricator.rb
Fabricator(:user) do
organization { Fabricate(:organization) }
email { "admin#example.com" }
password { "password" }
full_name { Faker::Name.name }
is_admin { true }
salt { "asdfghjkl123456789" }
crypted_password { Sorcery::CryptoProviders::BCrypt.encrypt("secret", "asdasdastr4325234324sdfds") }
activation_state { 'active' }
end
organization_fabricator.rb
Fabricator(:organization) do
name { Faker::Company.name }
website { Faker::Internet.url }
description { Faker::Lorem.paragraph }
access_code { Faker::Internet.password(10, 20) }
end
Here's the error i am getting when running the test:
Failure/Error: let!(:user) { Fabricate(:user) }
NoMethodError:
undefined method `crypted_password' for #<Organization:0x007f80ee0a44e0>
# ./spec/features/integration_spec.rb:4:in `block (2 levels) in <top (required)>'
You have authenticates_with_sorcery! in your Organization app.
If you don't intend to authenticate Organization, you should remove that line.
Cheers

Using FactoryGirl for resource that belongs to 2 other resources and validates their id's in Rails 4 app

My associations aren't so complex but I've hit a wall making them work with FactoryGirl:
Text: blast_id:integer recipient_id:integer
class Text < ActiveRecord::Base
belongs_to :blast
belongs_to :recipient, class_name: "User"
validates :blast_id, presence: true
validates :recipient_id, presence: true
end
Blast: content:string author_id:integer
class Blast < ActiveRecord::Base
belongs_to :author, class_name: "User"
has_many :texts
validates :author_id, presence: true
end
User: name:string, etc. etc.
class User < ActiveRecord::Base
has_many :blasts, foreign_key: "author_id"
validates :name, presence: true
end
In FactoryGirl I've got:
FactoryGirl.define do
factory :user, aliases: [:author, :recipient] do |u|
sequence(:name) { Faker::Name.first_name }
end
factory :blast do
author
content "Lorem ipsum"
ignore do
texts_count 1
end
after :build do |blast, evaluator|
blast.texts << FactoryGirl.build_list(:text, evaluator.texts_count, blast: nil, recipient: FactoryGirl.create(:user) )
end
end
factory :text do
blast
association :recipient, factory: :user
end
end
Finally, some specs which all fail because Texts is not valid
require 'spec_helper'
describe Text do
User.destroy_all
Blast.destroy_all
Text.destroy_all
let!(:user) { FactoryGirl.create(:user) }
let!(:blast) { FactoryGirl.create(:blast, author: user) }
let(:text) { blast.texts.first }
subject { text }
it { should be_valid }
describe "attributes" do
it { should respond_to(:blast) }
it { should respond_to(:recipient) }
its(:blast) { should == blast }
its(:recipient) { should == recipient }
end
describe "when blast_id is not present" do
before { text.blast_id = nil }
it { should_not be_valid }
end
describe "when recipient_id is not present" do
before { text.recipient_id = nil }
it { should_not be_valid }
end
end
All the specs fail on FactoryGirl blast creation with:
1) Text
Failure/Error: let!(:blast) { FactoryGirl.create(:blast, author: user) }
ActiveRecord::RecordInvalid:
Validation failed: Texts is invalid
# ./spec/models/text_spec.rb:8:in `block (2 levels) in <top (required)>'
I've tried various iterations of the association code in the FactoryGirl docs and other question answers like this one but my situation is different enough that I can't get it to work.
If you've made it this far, thank you! Super grateful for any leads.
Your factory for "blast" should look like
factory :blast do
author
content "Lorem ipsum"
ignore do
texts_count 1
end
after :build do |blast, evaluator|
blast.texts << FactoryGirl.build_list(:text, evaluator.texts_count, blast: blast, recipient: FactoryGirl.create(:user) )
end
end
In other words, you immediately create the correct "parent" by connecting the newly created blast to the newly created tekst
To further dry your code, have a look at https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#configure-your-test-suite, describing how to get rid of using "FactoryGirl." over and over again by setting
config.include FactoryGirl::Syntax::Methods
once in your settings

rspec association creation error

I have a model item has_many ratings and a ratings belongs_to item ratings belongs_to user I want to force a user who is creating an item to rate it too. Other users can then rate it later on. item and user have no association in my model.
I am doing the following in my item_spec which is giving me an error no implicit conversion of Symbol into Integer on line #item = Item.new(name: "Item1", below.
class Item < ActiveRecord::Base
has_many :ratings, dependent: :destroy, inverse_of: :item
accepts_nested_attributes_for :ratings, :allow_destroy => true
validates :name , :length => { minimum: 3 }
validates :category , :length => { minimum: 3 }
validates_presence_of :ratings
end
require 'spec_helper'
describe Item do
before do
#item = Item.new(name: "Item1",
url: "www.item1.com",
full_address: "Item1Address",
city: "Item1City",
country: "Item1Country",
category: "Item1Type",
ratings_attributes: {"rating" => "3", "comment" => "Ahh Good"} )
end
Also using FactoryGirl I am doing something like this
factory :item do
before_create do |r|
r.ratings<< FactoryGirl.build(:ratings, item: r )
end
name "Item1"
url "www.Item1.com"
full_address "Item1Address"
city "Item1City"
country "Item1Country"
category "Item1Category"
end
factory :ratings do
rating 3
comment "Its not that bad"
user
end
end
which again is not yeilding the desired result.
can anyone help me solve this problem please.Thanks!
Working Code, now having problem testing some association order, but at least the desired functionality working.
factory :item do
name "Item1"
url "www.Item1.com"
full_address "Item1Address"
city "Item1City"
country "Item1Country"
category "Item1Category"
end
factory :ratings, :class => 'Ratings' do
association :item, factory: :item, strategy: :build
user
rating 3
comment "Its not that bad"
end
factory :item_with_rating, parent: :item do
ratings {[FactoryGirl.create(:ratings)]}
end
Here is the spec file
require 'spec_helper'
describe Item do
before do
#item = FactoryGirl.create(:item_with_rating)
end
subject { #item }
it { should respond_to(:name) }
it { should respond_to(:url) }
it { should respond_to(:full_address)}
it { should respond_to(:city) }
it { should respond_to(:country) }
it { should respond_to(:category) }
it { should respond_to(:ratings) }
it { should_not respond_to(:type) }
it { should_not respond_to(:user_id) }
it { should be_valid }
There is no change in the Model file for item

Resources