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

标签 ruby-on-rails ruby rspec controller

我有两个模型:

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/

相关文章:

ruby - 如何使用 RSpec 在 gem 中测试 Sinatra 应用程序?

ruby-on-rails - 使用主键从数据库中的第三个模型检索数据

mysql - rails : Garble data as it leaves the database

html - wicked_pdf 不起作用——Ruby on Rails

ruby - 坚持 ruby​​ 绑定(bind)

ruby-on-rails - Ubuntu/Rails PG::InsufficientPrivilege: ERROR: permission denied to create database

ruby-on-rails - Ruby 使用 RubyZip 将远程文件存储在 Zip 中

ruby-on-rails - 从 MatchData 中获取数据作为匹配函数的结果

ruby - 带有选项的 paralell_rspec --exclude-pattern

ruby-on-rails - 如何为 Rails 编写 cucumber (最佳实践)。特征和步骤