Jos*_*pio 2 ruby controller rspec ruby-on-rails
我有两个型号:
class Solution < ActiveRecord::Base
belongs_to :user
validates_attachment_presence :software
validates_presence_of :price, :language, :title
validates_uniqueness_of :software_file_name, :scope => :user_id
has_attached_file :software
end
class User < ActiveRecord::Base
acts_as_authentic
validates_presence_of :first_name, :last_name, :primary_phone_number
validates_uniqueness_of :primary_phone_number
has_many :solutions
end
Run Code Online (Sandbox Code Playgroud)
我的路线看起来像这样:
map.resources :user, :has_many => :solutions
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试使用以下RSpec测试来测试我的解决方案控制器:
describe SolutionsController do
before(:each) do
@user = Factory.build(:user)
@solution = Factory.build(:solution, :user => @user)
end
describe "GET index" do
it "should find all of the solutions owned by a user" do
Solution.should_receive(:find_by_user_id).with(@user.id).and_return(@solutions)
get :index, :id => @user.id
end
end
end
Run Code Online (Sandbox Code Playgroud)
但是,这会给我带来以下错误:
ActionController::RoutingError in 'SolutionsController GET index should find all of the solutions owned by a user'
No route matches {:id=>nil, :controller=>"solutions", :action=>"index"}
Run Code Online (Sandbox Code Playgroud)
任何人都可以指出我如何测试这个,因为索引应该始终在特定用户的范围内调用?
Factory#build 构建类的实例,但不保存它,因此它还没有id.
所以,@user.id因为@user没有得救,所以是零.
因为@user.id是零,所以您的路线未激活.
尝试使用Factory#create.
before(:each) do
@user = Factory.create(:user)
@solution = Factory.create(:solution, :user => @user)
end
Run Code Online (Sandbox Code Playgroud)