Ryan
Ryan

Reputation: 667

RSpec "should be_valid" is not defined

I'm writing a model test in RSpec and this is the code I have:

require "spec_helper"

describe User do
before do
  @user = User.new(name: "Ryan", email: "[email protected]", password: "ryan", password_confirmation: "ryan")
end

subject { @user }

describe "Basic model properties" do
  it { should respond_to(:name) }
  it { should respond_to(:email) }
  it { should respond_to(:password_digest) }
  it { should respond_to(:password) }
  it { should respond_to(:password_confirmation) }
  it { should respond_to(:authenticate) }
  #it { should be_valid }
end

describe "when name is not present" do
  before { @user.name = "" }
  it { should_not be_valid }
end

However when I run it using bundle exec rspec spec/, I get an error saying "undefined method [] for nil:NilClass on the line where it says it { should_not be valid }. If I comment out that line then the test passes.

Why am I getting this problem?

Upvotes: 0

Views: 779

Answers (1)

mdenomy
mdenomy

Reputation: 333

Try changing

describe "when name is not present" do
  before { @user.name = "" }
  it { should_not be_valid }
end

To

describe "when name is not present" do
  before { subject.name = "" }
  it { should_not be_valid }
end

See rspec docs for more info https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/subject/explicit-subject#access-subject-from-before-block

Also you may want to look at shoulda-matchers (https://github.com/thoughtbot/shoulda-matchers) and then you wouldn't need to bother with doing anything special in the before block

describe "Basic model properties" do
  it { should respond_to(:name) }
  it { should respond_to(:email) }
  it { should respond_to(:password_digest) }
  it { should respond_to(:password) }
  it { should respond_to(:password_confirmation) }
  it { should respond_to(:authenticate) }
  it { should validate_presence_of(:name) }
end

Upvotes: 1

Related Questions