Factory Girl + Rspec: ArgumentError: wrong number of arguments (0 for 2) - ruby

I have a simple restaurant class that looks like this:
module Restaurant
class Identity
attr_reader :name, :location
def initialize (name, location)
#name = name
#location = location
end
end
end
My factory looks like this:
FactoryGirl.define do
factory :restaurant, :class => Restaurant::Identity do |f|
f.name "Alfredos"
f.location "Andheri"
end
end
And my test is written like this:
describe Restaurant::Identity do
subject { build(:restaurant) }
its(:name) {should_not be_nil}
its(:location) {should_not be_nil}
end
But when I run this, I get
1) Restaurant::Identity name
Failure/Error: subject { build(:restaurant) }
ArgumentError:
wrong number of arguments (0 for 2)
# ./lib/restaurant.rb:7:in `initialize'
# ./spec/restaurant_spec.rb:9:in `block (2 levels) in <top (required)>'
# ./spec/restaurant_spec.rb:11:in `block (2 levels) in <top (required)>'
Why is this happening? What am I doing wrong?

Ok so the solution is to use initialize_with in your factory girl setup:
FactoryGirl.define do
factory :restaurant, :class => Restaurant::Identity do |f|
f.name "Alfredos"
f.location "Andheri"
initialize_with { new(name, location) } # add this line
end
end
ref: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#custom-construction

Related

RSpec with FactoryGirl/Bot - undefined method 'user' on model that belongs to user through has_many :through

Trying to get into proper testing and figure out the ins and outs of basic RSpec with FactoryBot.
NOTE: The validation tests all passed previously and they're in the model files. I've just removed them for the sake of reducing clutter.
My models:
models/user.rb
has_many :fulfillments
has_many :milestones, through: :fulfillments
models/fulfillment.rb
has_many :milestones
belongs_to :user
models/milestone.rb
belongs_to :fulfillments
My Factories:
spec/factories/users.rb
require 'faker'
FactoryBot.define do
factory :user do
first_name Faker::Name.first_name
last_name Faker::Name.last_name
preferred_name Faker::Name.first_name
username Faker::Internet.user_name
email Faker::Internet.email
password 'password123'
password_confirmation 'password123'
factory :user_with_fulfillments do
transient do
fulfillments_count 3
end
after(:create) do |user, e|
create_list(:fulfillment_with_milestones, e.fulfillments_count, user: user)
end
end
end
end
spec/factories/fulfillments.rb
require 'faker'
FactoryBot.define do
factory :fulfillment do
title Faker::Lorem.words.join(' ')
description Faker::Lorem.sentences.join(' ')
promise Faker::Lorem.sentence
reason Faker::Lorem.sentence
association :user, factory: :user_with_fulfillments
trait :userless do
user nil
end
factory :fulfillment_with_milestones do
transient do
milestones_count 2
end
after(:create) do |fulfillment, e|
create_list(:milestone, e.milestones_count, fulfillment: fulfillment)
end
end
end
end
spec/factories/milestones.rb
require 'faker'
FactoryBot.define do
factory :milestone do
title Faker::Lorem.words.join(' ')
criteria Faker::Lorem.sentences.join("\n")
reason Faker::Lorem.sentence
deadline Faker::Date.forward(30)
association :fulfillment, factory: :fulfillment_with_milestones
end
end
One test that's giving me trouble (spec/models/milestone.rb)
require 'rails_helper'
RSpec.describe Milestone, type: :model do
it 'has a valid factory' do
expect(create(:milestone)).to be_valid
end
it 'validates attributes correctly' do
should validate_presence_of :fulfillment
should validate_presence_of :title
should validate_presence_of :criteria
end
end
Error I'm getting in ANY test that involves the milestones factory
Failures:
1) Fulfillment has a valid factory
Failure/Error: create_list(:milestone, e.milestones_count, fulfillment: fulfillment)
NoMethodError:
undefined method `user' for #<Milestone:0x00007f844d54f1b8>
# ./spec/factories/fulfillments.rb:22:in `block (4 levels) in <top (required)>'
# ./spec/factories/users.rb:19:in `block (4 levels) in <top (required)>'
# ./spec/models/fulfillment_spec.rb:6:in `block (2 levels) in <top (required)>'
2) Milestone has a valid factory
Failure/Error: expect(create(:milestone)).to be_valid
NoMethodError:
undefined method `user' for #<Milestone:0x00007f844d8d0b98>
# ./spec/models/milestone_spec.rb:6:in `block (2 levels) in <top (required)>'
3) Milestone validates attributes correctly
Failure/Error: should validate_presence_of :fulfillment
NoMethodError:
undefined method `user' for #<Milestone:0x00007f8450829700>
# ./spec/models/milestone_spec.rb:10:in `block (2 levels) in <top (required)>'
4) User can have fulfillments and milestones
Failure/Error: create_list(:milestone, e.milestones_count, fulfillment: fulfillment)
NoMethodError:
undefined method `user' for #<Milestone:0x00007f8450b7b9d0>
# ./spec/factories/fulfillments.rb:22:in `block (4 levels) in <top (required)>'
# ./spec/factories/users.rb:19:in `block (4 levels) in <top (required)>'
# ./spec/models/user_spec.rb:29:in `block (2 levels) in <top (required)>'
Finished in 0.26253 seconds (files took 5.19 seconds to load)
9 examples, 4 failures, 1 pending
Failed examples:
rspec ./spec/models/fulfillment_spec.rb:5 # Fulfillment has a valid factory
rspec ./spec/models/milestone_spec.rb:5 # Milestone has a valid factory
rspec ./spec/models/milestone_spec.rb:9 # Milestone validates attributes correctly
rspec ./spec/models/user_spec.rb:28 # User can have fulfillments and milestones
Mostly confused because I'm not sure where or why it's trying to call #user on an instance of Milestone. The factories create Fulfillments for a User, then Milestones for the Fulfillments.
PS: It's my first time posting to StackOverflow (I usually manage to find answers to my really simple questions) so feel free to let me know if there's anything I could do to make future questions clearer.
It turns out I'm an idiot. I had a
validates :user, :presence
on my Milestone model. No wonder why it was trying to call milestone.user
Forget this ever happened please. ]:
Try to define classes explicitly in your factories so that they are not guessed but known.
factory :user, class: User
and
factory :fulfillment, class: FulFillment

Why my ruby tests does not pass?

I have the following table TodoList :
class CreateTodoLists < ActiveRecord::Migration
def change
create_table :todo_lists do |t|
t.string :list_name
t.date :list_due_date
t.timestamps null: false
end
end
end
I create crud methods:
def create_todolist(params)
todolist = TodoList.create(params)
end
And i have the followging tests:
context "the code has to create_todolist method" do
it { is_expected.to respond_to(:create_todolist) }
it "should create_todolist with provided parameters" do
expect(TodoList.find_by list_name: "mylist").to be_nil
due_date=Date.today
assignment.create_todolist(:name=> 'mylist', :due_date=>due_date)
testList = TodoList.find_by list_name: 'mylist'
expect(testList.id).not_to be_nil
expect(testList.list_name).to eq "mylist"
expect(testList.list_due_date).to eq due_date
expect(testList.created_at).not_to be_nil
expect(testList.updated_at).not_to be_nil
end
end
When i launch the test give me the following errors:
assignment code has create_todolist method should create_todolist with provided parameters
Failure/Error: assignment.create_todolist(:name=> 'mylist', :due_date=>due_date)
ActiveRecord::UnknownAttributeError:
unknown attribute 'name' for TodoList.
# ./assignment/assignment.rb:25:in `create_todolist'
# ./spec/assignment_spec.rb:171:in `block (4 levels) in <top (required)>'
# ./spec/assignment_spec.rb:14:in `block (2 levels) in <top (required)>'
# ------------------
# --- Caused by: ---
# NoMethodError:
# undefined method `name=' for #<TodoList:0x007f96dd0d13f0>
# ./assignment/assignment.rb:25:in `create_todolist'
Finished in 0.14136 seconds (files took 1.66 seconds to load)
2 examples, 1 failure
Failed examples:
rspec ./spec/assignment_spec.rb:168 # Assignment rq03 rq03.2 assignment code has create_todolist method should create_todolist with provided parameters
I think it's because params attributes does not match exactly the same TodoList attributes. How to modify my create_todolist to change keys values ?
Your field is called list_name, but you're passing :name => 'myList'.
The same for due_date and list_due_date.
Should be
assignment.create_todolist(list_name:'mylist', list_due_date: due_date)

Undefined method error while running rspec test

All,
I am getting the following undefined method errors below when running my rspec tests. When I have gotten this error before I had a method misspelled or my order of execution caused it. I checked both along with some other posts on StackOverflow, but nothing helped. Can anyone offer any guidance?
Rspec Failures:
FFFF
Failures:
1) Post vote methods #up_votes counts the number of votes with value = 1
Failure/Error: expect(#post.up_votes ).to eq(3)
NoMethodError:
undefined method `up_votes' for #<Post:0x007fe92f381a38>
# ./spec/models/post_spec.rb:14:in `block (4 levels) in <top (required)>'
2) Post vote methods #down_votes counts the number of votes with values = -1
Failure/Error: expect(#post.down_votes ).to eq(2)
NoMethodError:
undefined method `down_votes' for #<Post:0x007fe92a18c228>
# ./spec/models/post_spec.rb:20:in `block (4 levels) in <top (required)>'
3) Post vote methods #points returns the sum of all down and up votes
Failure/Error: expect(#post.points ).to eq(1) # 3 - 2
NoMethodError:
undefined method `points' for #<Post:0x007fe92986c620>
# ./spec/models/post_spec.rb:26:in `block (4 levels) in <top (required)>'
4) Vote validations value validation only allows -1 or 1 as values
Failure/Error: expect(#post.up_votes).to eq((-1) || eq(1))
NoMethodError:
undefined method `up_votes' for nil:NilClass
# ./spec/models/vote_spec.rb:5:in `block (4 levels) in <top (required)>'
Post_rspec
require 'rails_helper'
describe Post do
describe "vote methods" do
before do
#post = Post.create(title: 'Post title', body: 'Post bodies must be pretty long.')
3.times { #post.votes.create(value: 1) }
2.times { #post.votes.create(value: -1) }
end
describe '#up_votes' do
it "counts the number of votes with value = 1" do
expect(#post.up_votes ).to eq(3)
end
end
describe '#down_votes' do
it "counts the number of votes with values = -1" do
expect(#post.down_votes ).to eq(2)
end
end
describe '#points' do
it "returns the sum of all down and up votes" do
expect(#post.points ).to eq(1) # 3 - 2
end
end
end
end
vote_spec file
describe Vote do
describe "validations" do
describe "value validation" do
it "only allows -1 or 1 as values" do
expect(#post.up_votes).to eq((-1) || eq(1))
end
end
end
end
Post.rb
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
has_many :votes
has_one :summary
belongs_to :user #means the post table has the user table's primary key in it
belongs_to :topic
mount_uploader :avatar, AvatarUploader
default_scope {order('created_at DESC')}
validates :title, length: {minimum: 5}, presence: true
validates :body, length: {minimum: 20}, presence: true
def markdown_title
(render_as_markdown).render(self.title).html_safe
end
def markdown_body
(render_as_markdown).render(self.body).html_safe
end
private
def render_as_markdown
renderer = Redcarpet::Render::HTML.new
extensions = {fenced_code_blocks: true}
redcarpet = Redcarpet::Markdown.new(renderer, extensions)
#return redcarpet
end
end
For the post_spec.rb errors, check the Post model (see file app/models/post.rb) has the following methods defined in it:
up_votes
down_votes
points
Consider including the code for post.rb in your original question too.
For the vote_spec.rb errors, there is no #post variable, it will be nil. This error message hints at this:
Failure/Error: expect(#post.up_votes).to eq((-1) || eq(1))
NoMethodError: undefined method `up_votes' for nil:NilClass

Rspec error: No route matches {:controller=>"user"}

Why am I getting that/how can I get around it?
Code is:
class UserController < ApplicationController
def index
#users=User.all
end
end
Spec is:
require 'spec_helper'
describe UserController do
describe "GET index" do
it "assigns #users" do
user = User.create(:email => 'bob#test.com', :password=>'12', :password_confirmation=> '12')
get :index
assigns(:users).should eq([user])
end
it "renders the index template" do
get :index
response.should render_template("index")
end
end
end
Failures:
1) UserController GET index assigns #users
Failure/Error: get :index
ActionController::RoutingError:
No route matches {:controller=>"user"}
# ./spec/controllers/user_controller_spec.rb:8:in `block (3 levels) in <top (required)>'
2) UserController GET index renders the index template
Failure/Error: get :index
ActionController::RoutingError:
No route matches {:controller=>"user"}
# ./spec/controllers/user_controller_spec.rb:13:in `block (3 levels) in <top (required)>'
Finished in 0.13146 seconds
2 examples, 2 failures
Routes are:
TimeTracker::Application.routes.draw do
devise_for :users
resources :users
root :to => 'users#index'
end
Your controller class name is in singular (UserController), it should be UsersController

Strange problem with factory girl

I have a model
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# name :string(255)
# title :string(255)
# content :text
# created_at :datetime
# updated_at :datetime
# abstract :text
# category_id :integer
# finalversion :boolean default(FALSE)
# published_date :date
#
class Post < ActiveRecord::Base
has_many :tags
belongs_to :category
validates :published_date, :presence => true
default_scope :order => 'created_at DESC'
accepts_nested_attributes_for :tags, :allow_destroy => :true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
def prev_post
self.class.first(:conditions => ["id < ?", id], :order => "id desc")
end
def next_post
self.class.first(:conditions => ["id > ?", id], :order => "id asc")
end
def seo_title
title.gsub(/\s+/,'_')
end
end
and a factory
FactoryGirl.define do
factory :post do
published_date Date.today
association :category, :factory => :category
title Forgery::LoremIpsum.words
name Forgery::LoremIpsum.word
content Forgery::LoremIpsum.words(100, :random => 250)
abstract Forgery::LoremIpsum.words(100, :random => 50)
finalversion true
end
end
and in the rails console I have no problem doing
FactoryGirl.create :post
to get a valid object and am able to access the *published_date* attribute. However in my spec
require 'spec_helper'
(1..5).map do |i|
title = "a title\t#{i}"
escape_title = "a_title_#{i}"
perma_link = "/posts/#{i}/title/#{escape_title}"
describe "A post with title '#{title}'" do
before do
#post = FactoryGirl.create :post, :id=>i, :title => title
visit '/posts'
end
it "should appear in all links with permalink #{perma_link}" do
within "section.post_#{#post.id}" do
page.should have_xpath(%Q%.//h1/a[#href="#{perma_link}"]%)
within "div.teaser" do
page.should have_xpath(%Q%.//a[#href="#{perma_link}"]%)
end
end
end
end
end
I get the backtrace error
5) A post with title 'a title 5' should appear in all links with permalink /posts/5/title/a_title_5
Failure/Error: #post = FactoryGirl.create :post, :id=>i, :title => title
NoMethodError:
undefined method `published_date=' for #<Post:0x000001047266b8>
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/activemodel-3.0.5/lib/active_model/attribute_methods.rb:364:in `method_missing'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/activerecord-3.0.5/lib/active_record/attribute_methods.rb:46:in `method_missing'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/bundler/gems/factory_girl-4f5f5df39a1b/lib/factory_girl/proxy/build.rb:13:in `set'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/bundler/gems/factory_girl-4f5f5df39a1b/lib/factory_girl/attribute/static.rb:12:in `add_to'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/bundler/gems/factory_girl-4f5f5df39a1b/lib/factory_girl/factory.rb:93:in `block in run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/bundler/gems/factory_girl-4f5f5df39a1b/lib/factory_girl/factory.rb:91:in `each'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/bundler/gems/factory_girl-4f5f5df39a1b/lib/factory_girl/factory.rb:91:in `run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/bundler/gems/factory_girl-4f5f5df39a1b/lib/factory_girl/syntax/methods.rb:54:in `create'
# ./spec/integration/posts_permalinks_spec.rb:12:in `block (3 levels) in <top (required)>'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/hooks.rb:29:in `instance_eval'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/hooks.rb:29:in `run_in'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/hooks.rb:64:in `block in run_all'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/hooks.rb:64:in `each'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/hooks.rb:64:in `run_all'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/hooks.rb:110:in `run_hook'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example_group.rb:191:in `block in eval_before_eachs'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example_group.rb:191:in `each'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example_group.rb:191:in `eval_before_eachs'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example.rb:144:in `run_before_each'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example.rb:48:in `block (2 levels) in run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example.rb:106:in `with_around_hooks'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example.rb:46:in `block in run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example.rb:99:in `block in with_pending_capture'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example.rb:98:in `catch'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example.rb:98:in `with_pending_capture'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example.rb:45:in `run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example_group.rb:262:in `block in run_examples'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example_group.rb:258:in `map'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example_group.rb:258:in `run_examples'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/example_group.rb:232:in `run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/command_line.rb:27:in `block (2 levels) in run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/command_line.rb:27:in `map'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/command_line.rb:27:in `block in run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/reporter.rb:12:in `report'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/command_line.rb:24:in `run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:55:in `run_in_process'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:46:in `run'
# /Users/bradphelan/.rvm/gems/ruby-1.9.2-p180#ingd/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:10:in `block in autorun'
I'm totally stumped on it. Any ideas
Brad
Did you run rake db:test:prepare? It looks to me like your Post model has published_date, but your Factory is saying it doesn't exist. Not running this rake task would be the major thing that would cause this.

Resources