Katherine Bangert
Katherine Bangert

Reputation: 23

Rails 4 model rspec for if conditional

I am new to Rails and I am trying to look in my object to see if a value is true in order to validate all the other items in the object. I certainly have if the person is a user, validate the name and email within the app/model. What is the best way to write a spec for this?

class Members < ActiveRecord::Base
    validates_presence_of :email, if: :is_user?
    validates_presence_of :first_name, if: :is_user?
    validates_presence_of :last_name, if: :is_user?

    def is_user?
        :is_user
    end
end

Upvotes: 2

Views: 4377

Answers (2)

Ashutosh Tiwari
Ashutosh Tiwari

Reputation: 998

You should use shouda matchers it would be sort and pretty:
Example taken from here Shoulda/RSpec matchers - conditional validation

context "if user" do
  before { subject.stub(:is_user?) { true } }
  it { should validate_presence_of(:name) }
  it { should validate_presence_of(:email) }
end

context "if not user" do
  before { subject.stub(:is_user?) { false } }
  it { should_not validate_presence_of(:name) }
  it { should validate_presence_of(:email) }
end

Upvotes: 3

rafb3
rafb3

Reputation: 1702

Do you have a field with the name "is_user" on the members table? It seems that method should return a boolean (true or false) while now it's returning a symbol which will always be evaluated to true, as an example, if you do

if :is_user
  puts "will always happen" # this will be printed
end

If there is the field on the database, then there's no need to create that method as rails generates methods with question mark for all boolean fields on the model database.

Now, to test that you can use a gem like shoulda_matchers or you can write your own tests like

describe "validations" do
  context "member is a user" do
    subject { Member.new(is_user: true) }

    it "validates presence of email" do
      subject.valid?
      expect(subject.errors["email"]).to include("can't be blank")
    end
  end

  context "member is not an user" do
    subject { Member.new(is_user: false) }

    it "doesn't require fields to have info" do
      subject.valid?
      expect(subject.errors["email"]).to_not include("can't be blank")
      expect(subject.errors["first_name"]).to_not include("can't be blank")
      expect(subject.errors["last_name"]).to_not include("can't be blank")
    end
  end
end

Upvotes: 3

Related Questions