请原谅我的生锈,第一次接触Rails和这个项目相当长一段时间。
Ruby版本:2.5.0
Rails版本:5.1.7
RSpec Version:3.9.3
FactoryBot Version:6.2.0
这是我的scripts_controller_spec.rb
文件与模型创建和问题的测试:
require 'rails_helper'
describe ScriptsController, type: :controller do
userID_1 = User.create!(
email: 'ueferfrfrf@u1.com',
password: 'useruser',
password_confirmation: 'useruser'
)
script1 = Script.create!(
name: 'YWoodcutter',
skill: 'Woodcutting',
bot_for: 'TRiBot',
game_for: 'Oldschool Runescape 07',
user_id: userID_1.id
)
script1.save
describe "GET #index" do
it "assigns @scripts" do
get :index
p script1
expect(assigns(:scripts)).to eq([script1])
end
end
运行测试时,上面的打印行输出如下所示:
#<脚本id: 1,名称:"YWoodcutter",技能:"Woodcutting", bot_for: "TRiBot", game_for: "Oldschool Runescape 07", user_id: 1, created_at:"
然而,我得到这个测试失败:
失败:
ScriptsController GET #index分配@scripts失败/错误:期望(分配(:脚本))。eq ([script1])
:[#<脚本id: 1,名称:"YWoodcutter",技能:"Woodcutting", bot_for: "TRiBot", game_for: "Oldschool Runescape 07",User_id: 1, created_at: "2021-10-19 08:29:43" updated_at: "2021-10-1908:29:43"祝辞]
有:# & lt; ActiveRecord::关系[]在(使用==比较)
我的scripts_controller.rb
索引函数看起来像这样:
class ScriptsController < ApplicationController
def index
@scripts = Script.order(:created_at)
end
如果你需要更多的信息,请告诉我,谢谢你的帮助!我认为Script
对象在调用index
动作之前没有被创建。因此,您将获得空的ActiveRecord::Relation. 在这种情况下让!应该可以解决你的问题
require 'rails_helper'
describe ScriptsController, type: :controller do
let!(:user_1) do
User.create!(
email: 'ueferfrfrf@u1.com',
password: 'useruser',
password_confirmation: 'useruser'
)
end
let!(:script1) do
Script.create!(
name: 'YWoodcutter',
skill: 'Woodcutting',
bot_for: 'TRiBot',
game_for: 'Oldschool Runescape 07',
user_id: user_1.id
)
end
describe "GET #index" do
before { get :index }
it "assigns @scripts" do
expect(assigns(:scripts)).to eq([script1])
end
end
end
根据当前的代码,似乎您没有调用所有脚本。
使用
### Controller
@scripts = Script.all.order(:created_at)
### Test
## Should use factories to create the records
let(:user) do
create(:user, email: 'ueferfrfrf@u1.com',
password: 'useruser',
password_confirmation: 'useruser')
end
let(:script) do
create(:script, name: 'YWoodcutter',
skill: 'Woodcutting',
bot_for: 'TRiBot',
game_for: 'Oldschool Runescape 07',
user: user)
end
应该修复它。