I can’t figure out why my 2nd example is passing even though it should be failing
this is my person_spec.rb:
require 'spec_helper'
describe Person do
it "must have a first name" do
subject { Person.new(first_name: "", last_name: "Kowalski") }
subject.should_not be_valid
end
it "must have a last name" do
subject { Person.new(first_name: "Jan") }
subject.should_not be_valid
end
end
this is my person.rb
class Person < ActiveRecord::Base
attr_accessible :first_name, :last_name
validates :first_name, presence: true
def full_name
return "#{@first_name} #{@last_name}"
end
end
My rspec output:
Person
must have a last name
must have a first name
Finished in 0.09501 seconds
2 examples, 0 failures
Randomized with seed 51711
What is even worse is that my further examples are failing/passing in a very unexpected way. It seems that somehow my subject is an instance of Person but with neither the first_name nor last_name assigned
I think you have two main issues here. First, if I’m not mistaken, you’re supposed to use
subjectin a group scope, but not within an actual spec. Here’s an example from the rspec docs:Note that the
subjectis declared outside of theitblock. So, I think it’s reasonable to see some unexpected behavior here. I haven’t dug into the source code here, but I have a feeling that would be educational.Secondly, your specs can be greatly simplified by following these guidelines from David Chelimsky. Your spec can look more like this:
Shorter, sweeter, and will probably work correctly.