我有两个模型:
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
我的路线如下所示:
map.resources :user, :has_many => :solutions
现在我尝试使用以下 RSpec 测试来测试我的解决方案 Controller :
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
但是,这给我带来了以下错误:
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"}
任何人都可以告诉我如何测试这一点,因为索引应该始终在特定用户的范围内调用?
最佳答案
Factory#build
构建该类的实例,但不保存它,因此它还没有 id。
因此,@user.id
为零,因为 @user
尚未保存。
因为 @user.id
为零,所以您的路由未激活。
尝试使用Factory#create
代替。
before(:each) do
@user = Factory.create(:user)
@solution = Factory.create(:solution, :user => @user)
end
关于ruby-on-rails - 使用关联测试 Rspec Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2303646/