gpt4 book ai didi

ruby-on-rails - 使用关联测试 Rspec Controller

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:27 24 4
gpt4 key购买 nike

我有两个模型:

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 为 nil,因为 @user 尚未保存。

因为 @user.id 是 nil,所以你的路由没有激活。

尝试改用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com