user2360003
user2360003

Reputation:

How to test model defaults in Rails with Rspec

I want to test that a new user when signed up, is not admin (as set by default: false in the migration). Here's my user_spec.rb so far:

require 'spec_helper'

describe User do

    before { @user = FactoryGirl.build(:user) }

    subject { @user }

  it { should respond_to(:username) }
  it { should respond_to(:email) }
  it { should respond_to(:admin) }

  describe "When username is too short" do
    before { @user.username = 'ab' }
    it { should_not be_valid }
  end

  describe "When username is too long" do
    before { @user.username = 'a' * 26 }
    it { should_not be_valid }
  end

  describe "Username is present" do
    before { @user.username = " " }
    it { should_not be_valid }
  end
end

I've tried

it "should not be admin" do
  expect { @user.admin }.to be_false
end

but it returns:

   expected: false value
        got: #<Proc:0x007ffc4b544a58@"

I suspect this is because I'm running tests based off a factory but it would defeat the purpose of testing a default value if I explicitly put 'admin false' into the factory.

How can I test default model values? Should I run through a sign up with capybara and then test that user?

Upvotes: 3

Views: 1795

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29379

You need to pass @user.admin to expect as a parameter, not within a block, as in:

expect(@user.admin).to be(false)

Passing a block is intended for those cases where you want to evaluate the side effects of an operation, such as updating a database, raising an error, etc.

Upvotes: 2

Related Questions