2013-03-16 77 views
3

我無法在Sinatra應用程序上運行一些rspec規範。我只是在學習Ruby,所以很遺憾,我不知道如何解決使用書中的代碼(Paul Dix的Ruby on Rails中的面向服務的設計)中的問題。RSpec規格未運行?

問題是這些測試沒有真正運行(我認爲)。從應用程序目錄中,我運行$ ruby spec/service_spec.rb,並且我沒有收到測試通過或失敗的跡象。我從文件/service.rb得到了幾條日誌消息,但是這是所有顯示的輸出。我放了一些puts調用來顯示之前的塊和它的塊沒有得到執行(儘管描述塊是)。

如果您想了解更多關於此代碼的信息,請查看the repository on Github

/spec/service_spec.rb:

ENV['SINATRA_ENV'] = 'test' 

require_relative '../service' 
require 'rspec' 
require 'rack/test' 

RSpec.configure do |conf| 
    conf.include Rack::Test::Methods 
end 

def app 
    Sinatra::Application 
end 

describe "service" do 
    puts 'describe 1' 
    before(:each) do 
    puts 'before 1' 
    User.delete_all 
    end 

    describe "GET on /api/v1/users/:id" do 
    puts 'describe 2' 
    before(:each) do 
     puts 'before 2' 
     User.create(
     :name => "paul", 
     :email => "[email protected]", 
     :password => "strongpass", 
     :bio => "rubyist") 
    end 

    it "should return a user by name" do 
     puts 'it 1' 
     get '/api/v1/users/paul' 
     last_response.should be_ok 
     attributes = JSON.parse(last_response.body)["user"] 
     attributes["name"].should == "paul" 
    end 

    it "should return a 404 for a user that doesn't exist" do 
     puts 'it 2' 
     get '/api/v1/users/foo' 
     last_response.status.should == 404 
    end 
    end 
end 

/service.rb:

require 'active_record' 
require 'sinatra' 
require_relative 'models/user' 
require 'logger' 

# log levels are DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN 
log = Logger.new(STDOUT) 
log.level = Logger::DEBUG 

# set up the environment 
env_index = ARGV.index("-e") 
env_arg = ARGV[env_index + 1] if env_index 
env = env_arg || ENV["SINATRA_ENV"] || "development" 
log.debug "env: #{env}" 

# set up database connection 
use ActiveRecord::ConnectionAdapters::ConnectionManagement 
databases = YAML.load_file("config/database.yml") 
ActiveRecord::Base.establish_connection(databases[env]) 
log.debug "#{databases[env]['database']} database connection established" 

# HTTP entry points 
# get a user by id 
get '/api/v1/users/:name' do 
    user = User.find_by_name(params[:name]) 
    if user 
     user.to_json 
    else 
     error 404, { error: "user not found" }.to_json 
    end 
end 

$紅寶石規格/ service_spec.rb輸出:

D, [2013-03-16T17:05:58.275276 #17685] DEBUG -- : env: test 
D, [2013-03-16T17:05:58.290885 #17685] DEBUG -- : db/test.sqlite3 database connection established 
describe 1 
describe 2 

任何想法?謝謝!

+1

你有'spec/spec_helper.rb'嗎?你在應用程序樹的頂部運行了'rspec --init'嗎? – 2013-03-16 21:36:28

+1

如果你這樣做了,試試運行'rspec spec/service_spec.rb'(或者'rspec'不帶參數)而不是'ruby spec/service_spec.rb'。它看起來像RSpec可能不會正確引導。 – 2013-03-16 21:37:20

+0

感謝Jim,解決了這個問題!不,我沒有spec_helper,所以我運行rspec --init(它創建了spec_helper文件),現在它正在工作。如果你發佈答案,我會給你信用。 – 2013-03-17 00:09:59

回答

4

每個評論的問題,這是通過運行rspec --init固定引導RSpec spec/spec_helper.rb文件修復。