gpt4 book ai didi

ruby-on-rails-3 - 如何编写不考虑质量分配的 rspec Controller 规范 model_mock

转载 作者:行者123 更新时间:2023-12-04 06:30:26 26 4
gpt4 key购买 nike

我正在使用 rspec 来测试使用已声明 attr_accessible 的模型的 Controller 。我不想测试 attr_accesible 是否正常工作(我的模型规范就是这样做的),但我确实想确保我的 Controller 没有执行批量分配。

具体来说,我有一个这样的模型:

class Post < ActiveRecord::Base
attr_accessible :body
validates :body, :presence => true,
validates :user, :presence => true
belongs_to :user
end

和一个稍微调整的生成 Controller (删除了 xml 格式行):
  def create
# this line keeps the rspec test mock happy
@post = Post.new(params[:post].merge(:user => current_user))

# Below are the correct lines of code for runtime for attr_accessible
# @post = Post.new(params[:post])
# @post.user = current_user

respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
else
format.html { render :action => "new" }
end
end
end

我有一个带有模拟 Controller 的 rspec 测试,该测试通过上述内容:
describe "POST create" do
describe "with valid params" do
it "assigns a newly created post as @post" do
Post.stub(:new).
with({'body' => 'hi there', 'user' => @user}) { mock_post(:save => true) }
post :create, :post => {'body' => 'hi there'}
assigns(:post).should be(mock_post)
end
end
end

我想要做的是更改 rspec 测试,以便在我注释掉第一个 @post 行并取消注释以下两个 @post 行时正确验证 Controller 。这样,我将验证 Controller 是否可以与真实模型一起正常工作,但我可以继续使用模拟进行测试。我已经尝试了几种方法并且似乎在兜圈子(是的,我是 Rails 和 Rspect 的新手:p)

提前谢谢了!

最佳答案

检查批量分配。你需要复制它。所以在请求中发送错误的用户 ID

post :create, :post => {'body' => 'hi there', 'user_id' => '2'}

然后确保您创建的帖子具有由 Controller 分配的 user_id(假设在此示例中其 id 不是 2)
assigns(:post)user_id.should be(current_user.id)

关于ruby-on-rails-3 - 如何编写不考虑质量分配的 rspec Controller 规范 model_mock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5480936/

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