Question

In my RSpec user_spec.rb one of my FactoryGirl factories seems valid and I can call should be_valid on it, and this test will pass (and will break if I put an empty string in the factory user_name).

describe User do
  it "has a valid factory" do
     # should be_valid works fine
     FactoryGirl.create(:user).should be_valid
  end  
  it "is invalid without a name" do
    # should_not_be_valid throws a NoMethodError
    FactoryGirl.build(:user, :user_name => nil).should_not_be_valid
  end
end

However when I call the above should_not_be_valid on FactoryGirl.build, the test fails:

  1) User is invalid without a name
     Failure/Error: FactoryGirl.build(:user, :user_name => nil).should_not_be_valid
     NoMethodError:
       undefined method `should_not_be_valid' for #<User id: nil, user_name: nil, created_at: nil, updated_at: nil>
     # ./spec/models/use

When it should instead pass, since a blank user_name is invalid. Here is what I have in my factories.rb:

FactoryGirl.define do  
  factory :user do
    user_name "Foo Bar"
  end
end

And my User model:

class User < ActiveRecord::Base
  has_one :musician

  validates :user_name, presence: true
end

How could should be_valid be working, but should_not_be_valid throws a NoMethodError?

I would really appreciate any help! I am running Rails 4, gem "rspec-rails", "~> 2.14.1", and gem 'factory_girl_rails', '4.3.0'

Been trying to puzzle this one out for awhile with no success...

Was it helpful?

Solution

Use space between should_not and be_valid:

FactoryGirl.build(:user, :user_name => nil).should_not be_valid
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top