好的,所以我正在开发我的第一个独立Rails应用程序,一个URL缩短器,我已经很好地混淆了自己。在我的模型中,我使用domain
和key
属性存储了一个简短的网址。这是我的模特:
# == 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 %>
答案 0 :(得分:4)
似乎在测试中,Shortener类无法访问域变量。你检查过你的测试数据库吗?