Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3854646
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T17:39:17+00:00 2026-05-19T17:39:17+00:00

Very simple example: Model: require ‘inventory’ class CustomerOrder < ActiveRecord::Base validates_presence_of :name validate :must_have_at_least_one_item,

  • 0

Very simple example:

Model:

require 'inventory'

class CustomerOrder < ActiveRecord::Base
  validates_presence_of :name
  validate :must_have_at_least_one_item, :items_must_exist
  before_save :convert_to_internal_items


  attr_accessor :items

  after_initialize do
    #convert the internal_items string into an array
    if internal_items
      self.items ||= self.internal_items.split(',').collect { |x| x.to_i }
    else 
      # only clobber it if it hasn't been set yet, like in the constructor
      self.items ||= []
    end
  end

  private
  def convert_to_internal_items
    #TODO: convert the items array into a string
    self.internal_items = self.items.join(',')
  end

  def must_have_at_least_one_item
    self.items.size >= 1
  end

  def items_must_exist
    self.items.all? do |item|
      Inventory.item_exists?(item)
    end
  end
end

Inventory is a singleton that should provide access to another service out there.

class Inventory 

  def self.item_exists?(item_id)
    # TODO: pretend real code exists here
    # MORE CLARITY: this code should be replaced by the mock, because the actual
    # inventory service cannot be reached during testing.
  end
end

Right now the service does not exist, and so I need to mock out this method for my tests. I’m having trouble doing this the Right Way(tm). I’d like to have it be configurable somehow, so that I can put in the mock during my tests, but have the normal code run in the real world.

There’s probably something I’m not wrapping my head around correctly.

EDIT: to be more clear: I need to mock the Inventory class within the validation method of the model. Eventually that will talk to a service that doesn’t exist right now. So for my tests, I need to mock it up as if the service I were talking to really existed. Sorry for the confusion 🙁

Here’s what I’d like to have in the specs:

describe CustomerOrder do
    it "should not accept valid inventory items" do
        #magical mocking that makes Inventory.item_exists? return what I want
        magic.should_receive(:item_exists?).with(1).and_return(false)
        magic.should_receive(:item_exists?).with(2).and_return(true)

        co = CustomerOrder.new(:name => "foobar", :items => [1,2]
        co.should_not be_valid
    end
    it "should be valid with valid inventory items" do
        #magical mocking that makes Inventory.item_exists? return what I want
        magic.should_receive(:item_exists?).with(3).and_return(true)
        magic.should_receive(:item_exists?).with(4).and_return(true)

        co = CustomerOrder.new(:name => "foobar", :items => [3,4]
        co.should be_valid
    end  
end

Using rails 3.0.3, rspec 2 and cucumber. Of course, only the rspec part matters.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T17:39:18+00:00Added an answer on May 19, 2026 at 5:39 pm

    The way I ended up solving this follows

    Inventory class:

    require  'singleton'
    
    class Inventory 
      include Singleton
    
      def self.set_mock(mock)
        @mock = mock
      end
    
      def self.item_exists?(item_id)
        return @mock.item_exists?(item_id) if @mock
        # TODO: how should I stub this out for the api
      end
    end
    

    CustomerOrder model:

    require 'inventory'
    
    class CustomerOrder < ActiveRecord::Base
      validates_presence_of :name
      validate :must_have_at_least_one_item, :items_must_exist
      before_save :convert_to_internal_items
    
    
      attr_accessor :items
    
      after_initialize do
        #convert the internal_items string into an array
        if internal_items
          self.items ||= self.internal_items.split(',').collect { |x| x.to_i }
        else 
          # only clobber it if it hasn't been set yet, like in the constructor
          self.items ||= []
        end
      end
    
      private
      def convert_to_internal_items
        #TODO: convert the items array into a string
        self.internal_items = self.items.join(',')
      end
    
      def must_have_at_least_one_item
        errors.add(:items, "Must have at least one item") unless self.items.size >= 1
      end
    
      def items_must_exist
        failed = self.items.find_all do |item|
          !Inventory.item_exists?(item)
        end
        if !failed.empty? then
          errors.add(:items, "Items with IDs: [#{failed.join(' ')}] are not valid")
        end
      end
    end
    

    CustomerOrder specs:

    require 'spec_helper'
    
    describe CustomerOrder do
        fixtures :all
    
        before do
            fake = double('fake_inventory')
            fake.stub(:item_exists?) do |val|
                case val
                when 1
                    true
                when 2
                    true
                when 3
                    false
                end
            end
            Inventory.set_mock(fake)
            #GRR, skipping my fixtures right now
            @valid_order = CustomerOrder.new(:name => "valid order",
                                                                 :items => [1,2])
        end
    
        it "should require a name and at least one item" do
            co = CustomerOrder.new(:name => "valid", :items => [1])
            co.should be_valid
        end
    
        it "should not be valid without any items" do
            @valid_order.items = []
            @valid_order.should_not be_valid
        end
    
        it "should not be valid without a name" do
            @valid_order.name = nil
            @valid_order.should_not be_valid
        end
    
        it "should expose items instead of internal_items" do
            @valid_order.should respond_to(:items)
        end
    
        it "should be able to treat items like an array" do
            @valid_order.items.size.should == 2
            @valid_order.items.should respond_to(:<<)
            @valid_order.items.should respond_to(:[])
        end
    
        it "should store items internally as a comma separated string" do
            co = CustomerOrder.new(:name => "name", :items => [1,2])
            co.save!
            co.internal_items.should == "1,2"
        end
    
        it "should convert items to internal_items for saving" do
            co = CustomerOrder.new(:name => "my order",
                                                         :items => [1,2])
            co.name.should == "my order"
            co.save!
    
            co.internal_items.should == "1,2"
        end
    
        it "loads items from the database into the items array correctly" do
            co = CustomerOrder.new(:name => "woot", :items => [2,1])
            co.save.should == true
    
            co2 = CustomerOrder.find_by_name("woot")
            co2.items.should == [2,1]
        end
    
        it "is not valid with items that don't exist" do
            @valid_order.items = [3,2,1]
            @valid_order.should_not be_valid
        end
    
        it "ensures that items exist to be valid" do
            @valid_order.items = [1,2]
    
            @valid_order.should be_valid
        end
    end
    

    This solution works, although it’s probably not the best way to inject a mock into the Inventory Service at runtime. I’ll try to do a better job of being more clear in the future.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Have a look at this very simple example WPF program: <Window x:Class=WpfApplication1.Window1 xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
Below I have a very simple example of what I'm trying to do. I
I'm looking for a very simple example of active record in .NET (code samples
Here's a very simple Prototype example. All it does is, on window load, an
I need a very simple and clear example of how to create an OCX
Take a very simple case as an example, say I have this URL: http://www.example.com/65167.html
This seems like a very simple and a very common problem. The simplest example
Very simple question, is there any cloud server enviroments avaliable these days for us
This very simple code gives me tons of errors: #include <iostream> #include <string> int
A very simple ?: operator in C#, combined with a simple array and LINQ

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.