RSpec规格没有运行?

时间:2013-03-16 21:14:26

标签: ruby rspec sinatra

我在Sinatra应用程序上运行一些rspec规范时遇到了麻烦。我只是在学习Ruby,所以遗憾的是我不太了解我从书中的代码中解决的问题(Ruby on Rails中的服务导向设计,Paul Dix)。

问题是这些测试并没有真正运行(我认为)。从app目录,我运行$ 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 => "paul@pauldix.net",
        :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

$ ruby​​ spec / 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 个答案:

答案 0 :(得分:4)

根据问题的评论,通过运行rspec --init以使用spec/spec_helper.rb文件引导RSpec来解决此问题。