【发布时间】:2025-11-22 06:30:01
【问题描述】:
我有以下create方法,它创建一个新的活动数组,循环活动的参数,将action_type设置为参数action_type。然后使用action_type 创建一个新实例。然后我将局部变量活动推入@activities 数组,然后为 cmets 和警报创建一个新实例。
def create
@activities = []
params[:activities].each do |act|
action_type = act[:action_type]
activity = Activity.create(action_type: action_type)
@activities << activity
Comment.create(comment_text: act[:comment])
Alert.create(alert_id: act[:alert_id])
end
render json: @activities
end
当我尝试运行以下 RSpec 测试时出现问题
let(:valid_hash_attributes) do
[
{
action_type:"Right-sized next generation application",
entered_by:"Mrs. Cortney Goyette",
alert_id:1,
comment:"This is a acomment"
}
]
end
let(:valid_session) { {} }
describe "POST create" do
describe "with valid params" do
it "creates a new Activity" do
expect {
post :create, {:activities => valid_hash_attributes}, valid_session
}.to change(Activity, :count).by(1)
end
it "assigns a newly created activity as @activity" do
post :create, {:activities => valid_hash_attributes}, valid_session
assigns(:activity).should be_a(Activity)
assigns(:activity).should be_persisted
end
end
end
end
我得到以下输出:
NoMethodError: 未定义的方法
each' for nil:NilClass ./app/controllers/activities_controller.rb:30:increate' ./spec/controllers/activities_controller_spec.rb:87:in `(root)'
真正奇怪的是,在RSpec日志中显示我们创建的这些对象如下图所示:
参数:{"activities"=>[{"action_type"=>"右下角 代申请", "entered_by"=>"Mrs.科特尼·戈耶特”, "alert_id"=>"1", "comment"=>"这是一条评论"}]} 保存点 (0ms) SAVEPOINT active_record_1 SQL (1.0ms) INSERT INTO "activities" (“action_type”、“created_at”、“updated_at”、“user_id”)值 ('合适大小的下一代应用程序', '2013-10-18 13:17:46.129000', '2013-10-18 13:17:46.129000', 1) 保存点 (0ms) RELEASE SAVEPOINT active_record_1 (0ms) SELECT name FROM sqlite_master WHERE type = 'table' AND name = "cmets" 保存点 (0ms) SAVEPOINT active_record_1 SQL (1.0ms) INSERT INTO "cmets" ("comment_text", "created_at", "updated_at") VALUES ('这是一个 评论','2013-10-18 13:17:46.212000','2013-10-18 13:17:46.212000') 保存点 (1.0ms) 释放保存点 active_record_1 (1.0ms) 选择 name FROM sqlite_master WHERE type = 'table' AND name = "alerts" 保存点 (0ms) SAVEPOINT active_record_1 SQL (1.0ms) INSERT INTO “警报”(“alert_id”,“created_at”,“updated_at”)值(1, '2013-10-18 13:17:46.332000', '2013-10-18 13:17:46.332000') 保存点 (0ms) 释放保存点 active_record_1
实际上很困惑为什么这个测试没有通过。
【问题讨论】:
标签: ruby-on-rails rspec