Ruby basic RSpec test does not pass - ruby

I'm not able to understand why the following Rspec test does not pass -
require "rspec"
require_relative "file-to-be-tested"
describe Customer do
it "is valid with firstname" do
customer = Customer.new("handy")
expect(customer).to be_valid
end
end
for the corresponding Class definition -
class Customer
attr_reader :firstname
def initialize(firstname)
#firstname = firstname
end
end
these two code snippets are in separate files in the same folder, so when i run ~rspec <first-filename> in the terminal, I get the following error -
F
Failures:
1) Customer is valid with firstname
Failure/Error: expect(customer).to be_valid
expected #<Customer:0x007f90e50f3110> to respond to `valid?`
# ./poodr/poodr_rspec.rb:8:in `block (2 levels) in <top (required)>'
Finished in 0.00551 seconds (files took 0.52876 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./poodr/poodr_rspec.rb:6 # Customer is valid with firstname

be_valid is an rspec-rails method, but it looks like you're using just straight rspec. you could do something like:
require "rspec"
require_relative "file-to-be-tested"
describe Customer do
it "is valid with firstname" do
expect { Customer.new('handy') }.to_not raise_error
end
end

What are you expecting the to be_valid test to do? The issue is that the Customer class has no method called valid? which your test is trying to test.
A hack to move your test along if your doing test driven development:
class Customer
def valid?
true
end
end
You now have a method called valid and your test will pass. Obviously it shouldn't always be true so your next step would be to expand the definition of valid?. What check needs to be done to know if a customer is valid or not?

Related

How to test a Ruby Roda app using RSpec to pass an argument to app.new with initialize

This question probably has a simple answer but I can't find any examples for using Roda with RSpec3, so it is difficult to troubleshoot.
I am using Marston and Dees "Effective Testing w/ RSpec3" book which uses Sinatra instead of Roda. I am having difficulty passing an object to API.new, and, from the book, this is what works with Sinatra but fails with a "wrong number of arguments" error when I substitute Roda.
Depending on whether I pass arguments with super or no arguments with super(), the error switches to indicate that the failure occurs either at the initialize method or in the call to Rack::Test::Methods post in the spec.
I see that in Rack::Test, in the Github repo README, I may have to use Rack::Builder.parse_file("config.ru") but that didn't help.
Here are the two errors that rspec shows when using super without brackets:
Failures:
1) MbrTrak::API POST /users when the user is successfully recorded returns the user id
Failure/Error: post '/users', JSON.generate(user)
ArgumentError:
wrong number of arguments (given 1, expected 0)
# ./spec/unit/app/api_spec.rb:21:in `block (4 levels) in <module:MbrTrak>'
And when using super():
1) MbrTrak::API POST /users when the user is successfully recorded returns the user id
Failure/Error: super()
ArgumentError:
wrong number of arguments (given 0, expected 1)
# ./app/api.rb:8:in `initialize'
# ./spec/unit/app/api_spec.rb:10:in `new'
# ./spec/unit/app/api_spec.rb:10:in `app'
# ./spec/unit/app/api_spec.rb:21:in `block (4 levels) in <module:MbrTrak>'
This is my api_spec.rb:
require_relative '../../../app/api'
require 'rack/test'
module MbrTrak
RecordResult = Struct.new(:success?, :expense_id, :error_message)
RSpec.describe API do
include Rack::Test::Methods
def app
API.new(directory: directory)
end
let(:directory) { instance_double('MbrTrak::Directory')}
describe 'POST /users' do
context 'when the user is successfully recorded' do
it 'returns the user id' do
user = { 'some' => 'user' }
allow(directory).to receive(:record)
.with(user)
.and_return(RecordResult.new(true, 417, nil))
post '/users', JSON.generate(user)
parsed = JSON.parse(last_response.body)
expect(parsed).to include('user_id' => 417)
end
end
end
end
end
And here is my api.rb file:
require 'roda'
require 'json'
module MbrTrak
class API < Roda
def initialize(directory: Directory.new)
#directory = directory
super()
end
plugin :render, escape: true
plugin :json
route do |r|
r.on "users" do
r.is Integer do |id|
r.get do
JSON.generate([])
end
end
r.post do
user = JSON.parse(request.body.read)
result = #directory.record(user)
JSON.generate('user_id' => result.user_id)
end
end
end
end
end
My config.ru is:
require "./app/api"
run MbrTrak::API
Well roda has defined initialize method that receives env as an argument which is being called by the app method of the class. Looks atm like this
def self.app
...
lambda{|env| new(env)._roda_handle_main_route}
...
end
And the constructor of the app looks like this
def initialize(env)
When you run your config.ru with run MbrTrack::API you are actually invoking the call method of the roda class which looks like this
def self.call(env)
app.call(env)
end
Because you have redefined the constructor to accept hash positional argument this no longer works and it throws the error you are receiving
ArgumentError:
wrong number of arguments (given 0, expected 1)
Now what problem are you trying to solve, if you want to make your API class configurable one way to go is to try out dry-configurable which is part of the great dry-ruby gem collection.
If you want to do something else feel free to ask.
It has been a long time since you posted your question so hope you will still find this helpful.

Rails 4, rspec 3: model validation test

I have an organization object that has attributes name, doing_business_as. I need to validate that the name is not the same as doing_business_as.
# app/models/organization.rb
class Organization < ActiveRecord::Base
validate :name_different_from_doing_business_as
def name_different_from_doing_business_as
if name == doing_business_as
errors.add(:doing_business_as, "cannot be same as organization name")
end
end
end
I have a matching rspec file that verifies this:
# spec/models/organization_spec.rb
require "rails_helper"
describe Organization do
it "does not allow NAME and DOING_BUSINESS_AS to be the same" do
organization = build(:organization, name: "same-name", doing_business_as: "same-name")
expect(organization.errors[:doing_business_as].size).to eq(1)
end
end
When I run the spec, however, it fails and this is what I get:
$ rspec spec/models/organization_spec.rb
Organization
does not allow NAME and DOING_BUSINESS_AS to be the same (FAILED - 1)
Failures:
1) Organization validations does not allow NAME and DOING_BUSINESS_AS to be the same
Failure/Error: expect(organization.errors[:doing_business_as].size).to eq(1)
expected: 1
got: 0
(compared using ==)
# ./spec/models/organization_spec.rb:113:in `block (3 levels) in <top (required)>'
Finished in 0.79734 seconds (files took 3.09 seconds to load)
10 examples, 1 failure
Failed examples:
rspec ./spec/models/organization_spec.rb:110 # Organization validations does not allow NAME and DOING_BUSINESS_AS to be the same
I was expecting the spec to pass and ensure that the 2 attributes cannot be the same. In the Rails console I can mimic the expected behavior, but I can't seem to get the spec to "fail" successfully.
I also checked via the Rails Console that it works as expected:
$ rails c
> o = Organization.new(name: "same", doing_business_as: "same")
> o.valid?
=> false
> o.errors[:doing_business_as]
=> ["cannot be the same as organization name"]
So I know the functionality is there, but I can't get a workable test...
You need to use build method instead of create method.
# spec/models/organization_spec.rb
require "rails_helper"
describe Organization do
it "does not allow NAME and DOING_BUSINESS_AS to be the same" do
organization = build(:organization, name: "same-name", doing_business_as: "same-name")
organization.valid?
expect(organization.errors[:doing_business_as].size).to eq(1)
end
end
or
# spec/models/organization_spec.rb
require "rails_helper"
describe Organization do
it "does not allow NAME and DOING_BUSINESS_AS to be the same" do
organization = build(:organization, name: "same-name", doing_business_as: "same-name")
expect(organization).to be_invalid
end
end

undefined method `valid?' for #<Class:0x94b626c>

Why am getting this error? How to fix?
1) User should exist
Failure/Error: User.should be_valid
NoMethodError:
undefined method `valid?' for #<Class:0x94b626c>
Test is:
require 'spec_helper'
describe User do
it "should exist" do
User.should be_valid
end
it "should not allow me to create a new user without required fields" do
User.new(:email => 'bob').should_not be_valid
end
end
The second test works ok, how can I get the first one to pass? I just want it to check that the model exists
Testing a class implicitly tests that it exists. Both code samples will error out if the class doesn't exist. The first is unnecessary.
Replace User.should be_valid with User.new.should be_valid in the first test. RSpec is calling valid? on the User class instead of an instance of it.

payroll_items_controller_spec.rb:18:in `block (2 levels) displayed in Rspec Controller code

Below is the controller code in rspec for a master item.
To be very frank I'm very new to Ruby with a little knowledge of coding.
require 'spec_helper'
describe PayrollItemsController , "with valid params" do
before(:each) do
#payroll_item = mock_model(PayrollItem, :update_attributes => true)
PayrollItem.stub!(:find).with("1").and_return(#payroll_item)
end
it "should find PayrollItem and return object" do
PayrollItem.should_receive(:find).with("0").and_return(#payroll_item)
end
it "should update the PayrollItem object's attributes" do
#payroll_item.should_receive(:update_attributes).and_return(true)
end
end
When I run the controller code, following error displayed:
(Mock "PayrollItem_1001").update_attributes(any args)
expected: 1 time
received: 0 times
./payroll_items_controller_spec.rb:18:in `block (2 levels) in '
You have to actually make a request (get, post, put etc.) to the controller in order for the mock to have anything to check.
So for example:
it "should find PayrollItem and return object" do
PayrollItem.should_receive(:find).with("0").and_return(#payroll_item)
put :update, :id => "0"
end
In addition to that, looking at your code, you have some inconsistencies with your return values: in your before block you're stubbing PayrollItem.find with an id of 1 to return something, and then in your first spec you're mocking it with an id of 0 to return the same thing.
It's fine to both stub and mock the same method because they fulfill different functions: a stub makes sure that the code runs smoothly, while the mock actually checks an expectation. However, you should be stubbing/mocking it for the same argument, so that all the specs using this before block are testing the same thing.

ArgumentError in rspec

I want to write some tree data structure in ruby. The class file:
class Tree
attr_accessor :node, :left, :right
def initialize(node, left=nil, right=nil)
self.node=node
self.left=left
self.right=right
end
end
The rspec file:
require 'init.rb'
describe Tree do
it "should be created" do
t2=Tree.new(2)
t1=Tree.new(1)
t=Tree.new(3,t1,t2)
t.should_not be nil
t.left.node should eql 1
t.right.node should eql 2
end
end
Rspec keeps complaining:
1) Tree should be created
Failure/Error: t.left.node should eql 1
ArgumentError:
wrong number of arguments (0 for 1)
# ./app/tree.rb:3:in `initialize'
# ./spec/tree_spec.rb:9:in `block (2 levels) in <top (required)>'
Why?? I move the spec code into the class file and it works out. What is wrong?
Believe it or not, the problem is two missing dots in your rspec. These lines:
t.left.node should eql 1
t.right.node should eql 2
should be this:
t.left.node.should eql 1
t.right.node.should eql 2
Insert that period before should, and your spec should pass.
Here's what's going on. The should method works on any value, but if you call it bare, like this:
should == "hello"
it will operate on the subject of your test. What's the subject? Well, you can set the subject to whatever you want using the subject method, but if you don't, rspec will assume the subject is an instance of whatever class is being described. It sees this at the top of your spec:
describe Tree
and tries to create a subject like this:
Tree.new
which blows up, since your initialize won't work without any arguments; it needs at least one. The result is a pretty cryptic error if you didn't intend to write a should with an implicit subject.

Resources