如何在RSpec中将一个方法的输出传递给另一个方法?

时间:2016-09-09 11:43:29

标签: rspec

我有一个名为db_conn.rb的班级,其中有2个方法 1.一种方法是检查是否建立了数据库连接,称为is_conn? 2.另一个是关闭数据库连接,即close_conn

现在我想为rspecclose_conn。我的逻辑是运行close_conn,然后调用is_conn?来检查应该是false的布尔值。

以下是我的spec文件。我需要更多的指导才能实现这一目标。

describe DdModule::DbConnn do
   before(:context) { 
       puts "Testing DB connection..."
       @obj = DbModule::DbConn.new("hostname", "instance", "port", "user", "pass")
    }


it "connect_db constructor takes five parameters and returns true if connection establishes" do
    expect(@obj.is_conn?).to eq true
end

it "connect_db close_connection should close the connection and is_connection should return false" do
    @obj.close_conn
    expect(@db_obj.is_conn?).to eq false
end

我看到以下输出:

rspec
Testing DB connection...
Oracle Connection user@jdbc:oracle:thin:@host:1521/instance initialized..
.FFF

Failures:

1) DbModule::DbConn close_connection should close the connection and is_conn should return false
 Failure/Error: expect(@obj.is_conn?).to eq false

   expected: false
        got: true

   (compared using ==)
 # ./spec/conn_db_spec.rb:21:in `(root)'
Finished in 0.2 seconds (files took 0.27 seconds to load)
2 examples, 1 failures

1 个答案:

答案 0 :(得分:1)

如果它是你希望用另一个实例方法改变的实例方法,你需要写这样的期望(我在本地做了一个测试类以确保它有效)。

    _getFromDataStore: function() {
        return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
    }, 

    _saveToDataStore: function() {
        return localStorage.setItem(STORAGE_ID, JSON.stringify(dataStore));
    }, 

如果是我,我会像这样编写完整的规范

expect {@obj.close_conn}.to change(@obj, :is_conn?).from(true).to(false)
相关问题