2012-07-15 90 views
1

我有这样的模块:RSpec的,如何测试初始化​​模块内部

module TicketsPresenters 

    class ShowPresenter 
     def initialize(ticket_or_id = nil) 
     unless ticket_or_id.nil? 
      if ticket_or_id.is_a?(Ticket) 
      @ticket = ticket_or_id 
      else 
      @ticket = Ticket.find(ticket_or_id) 
      end 
     end 
    end 

end 

我想测试是否initialize()方法适当地设置上述目的,当我通过一个整数或直接在对象实例。

+0

我的建议是,您不能提供传递工单标识或工单对象的功能。如果在初始化演示者时有ID,那么只需实例化票证对象并始终将其传入。无需增加复杂性。 – th3mus1cman 2012-07-15 15:24:33

回答

2

可能有十几种方法来回答这个问题,但我会给你我更喜欢的RSpec格式。

以下假设您在ShowPresenter类中拥有读票方法(即attr_reader :ticket)。它还假定您正在创建具有有效参数的Ticket对象,以便保存它。

describe TicketsPresenters::ShowPresenter do 
    context '#initialize' do 
    let!(:ticket) { Ticket.create!(...) } 

    context 'with an id' do 
     subject { TicketsPresenters::ShowPresenter.new(ticket.id) } 
     its(:ticket) { should == ticket } 
    end 

    context 'with a Ticket object' do 
     subject { TicketsPresenters::ShowPresenter.new(ticket) } 
     its(:ticket) { should == ticket } 
    end 

    context 'with nothing' do 
     subject { TicketsPresenters::ShowPresenter.new } 
     its(:ticket) { should be_nil } 
    end 
    end 
end 

注:我的FactoryGirl粉丝,所以我会个人更喜欢使用Factory.create(:ticket)超过Ticket.create!(...),因为它允许你在一个地方定义一个有效的票据对象,你不需要在更新它所有的测试该定义是否改变。

人们采取的另一个测试位置是根本不使用数据库持久性。这可能不是我对Ruby或RSpec新手建议的概念,因为它有点难以解释,并且需要更多的OOP知识。好处在于它消除了数据库依赖性,并且测试更快更独立。

describe TicketsPresenters::ShowPresenter do 
    context '#initialize' do 
    let(:ticket) { mock(:ticket, id: 1) } 

    before do 
     ticket.stub(:is_a?).with(Ticket) { true } 
     Ticket.stub(:find).with(ticket.id) { ticket } 
    end 

    context 'with an id' do 
     subject { TicketsPresenters::ShowPresenter.new(ticket.id) } 
     its(:ticket) { should == ticket } 
    end 

    context 'with a Ticket object' do 
     subject { TicketsPresenters::ShowPresenter.new(ticket) } 
     its(:ticket) { should == ticket } 
    end 

    context 'with nothing' do 
     subject { TicketsPresenters::ShowPresenter.new } 
     its(:ticket) { should be_nil } 
    end 
    end 
end