好吧,所以我正在开发我的第一个单独的Rails应用程序,一个URL缩写器,我已经很困惑了。在我的模型中,我使用domain
和key
属性存储了一个简短的URL。这是我的型号:
# == Schema Information
# Schema version: 20110601022424
#
# Table name: shorteners
#
# id :integer not null, primary key
# url :string(255)
# key :string(255)
# created_at :datetime
# updated_at :datetime
# domain :string(255)
#
class Shortener < ActiveRecord::Base
attr_accessible :url
validates :url, :presence => true, :uniqueness => true, :uri_format => true
before_save :set_autogenerated_info
def shortlink
"http://#{domain}/#{key}"
end
private
def set_autogenerated_info
return unless new_record? #This only gets set one time
domain = get_random_domain
key = get_next_key(domain)
write_attribute(:domain, domain)
write_attribute(:key, key)
end
def get_random_domain
#commented out magic to grab random domain from pool
end
def get_next_key(domain)
#commented out magic to generate next unique key
end
end
我目前的方法似乎把我的controller_spec:中的这个测试用例搞砸了
require 'spec_helper'
describe ShortenersController do
render_views
describe "GET show" do
before(:each) do
@shortener = Factory(:shortener)
end
it "should find the right shortener" do
get :show, :id => @shortener
assigns(:shortener).should == @shortener
end
end
end
它给我的错误信息是:
Failures:
1) ShortenersController GET show should find the right shortener
Failure/Error: get :show, :id => @shortener
ActionView::Template::Error:
undefined local variable or method `domain' for #<Shortener:0x00000004a04548>
# ./app/models/shortener.rb:25:in `shortlink'
# ./app/views/shorteners/show.html.erb:10:in `_app_views_shorteners_show_html_erb___556550686459204284_38799300_3170414004415921977'
# ./spec/controllers/shorteners_controller_spec.rb:32:in `block (3 levels) in <top (required)>'
我可以通过在attr_accessible
行上方添加以下内容来通过测试用例:
attr_reader :domain, :key
但这确实做了一些非常疯狂的事情,比如不在应用程序的视图中显示域/密钥属性,甚至不允许我直接从Rails控制台中的模型访问它们:
Loading development environment (Rails 3.0.7)
>> s = Shortener.new(:url => 'http://www.stackoverflow.com')
=> #<Shortener id: nil, url: "http://www.stackoverflow.com", key: nil, created_at: nil, updated_at: nil, domain: nil>
>> s.save
=> true
>> s
=> #<Shortener id: 12, url: "http://www.stackoverflow.com", key: l, created_at: "2011-06-02 16:35:01", updated_at: "2011-06-02 16:35:01", domain: "localhost">
>> s.domain
=> nil
>> s.key
=> nil
>> s.shortlink
=> "http:///"
更新-添加的视图:
<p id="notice"><%= notice %></p>
<p>
<b>Url:</b>
<%= @shortener.url %>
</p>
<p>
<b>Shortened Link:</b>
<a href="<%= @shortener.shortlink %>"><%= @shortener.shortlink %></a>
</p>
<%= link_to 'Edit', edit_shortener_path(@shortener) %> |
<%= link_to 'Back', shorteners_path %>
在测试中,Shortener类似乎无法访问域变量。你检查过你的测试数据库了吗?