gpt4 book ai didi

ruby-on-rails - 测试 'create' Controller 操作的正确方法是什么?

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

我正在使用 Ruby on Rails 3.2.2、Rspec 2.9.0 和 RspecRails 2.9.0。我想测试 create Controller 操作,但我不知道如何使其成为“正确”/“正确”的方式。我“搭建”了模型、 Controller 、 View ……文件,因此在这些文件中我拥有由 Ruby on Rails 生成器生成的通用代码;在我的规范文件中,我有:

it "assigns @article" do
new_article = FactoryGirl.build(:article)
Article.should_receive(:new).and_return(new_article)
post :create
assigns[:article].should eq(new_article)
end

也许,(注意:上面的代码与我用来测试new Controller Action 的代码几乎相同)测试create Controller 操作将在 post :create 操作期间传递一些属性值,而不是像我上面那样继续,但我不知道如何做到这一点以及它是否是“正确”/“适当”的制作方式。

那么,测试“创建” Controller 操作的正确方法是什么?

最佳答案

我是这样做的:

describe "#create" do
before { post :create, { "my_model"=> { "name"=>"name" } } }
specify("should created one my_model") { change{ MyModel.count }.from(0).to(1) }
end

Aaron Sumner 最近写了这本书 Everyday Rails Testing with RSpec有一个article at his blog .他是这样描述的:

describe "POST create" do
context "with valid attributes" do
it "creates a new contact" do
expect{
post :create, contact: Factory.attributes_for(:contact)
}.to change(Contact,:count).by(1)
end

it "redirects to the new contact" do
post :create, contact: Factory.attributes_for(:contact)
response.should redirect_to Contact.last
end
end

context "with invalid attributes" do
it "does not save the new contact" do
expect{
post :create, contact: Factory.attributes_for(:invalid_contact)
}.to_not change(Contact,:count)
end

it "re-renders the new method" do
post :create, contact: Factory.attributes_for(:invalid_contact)
response.should render_template :new
end
end
end

关于ruby-on-rails - 测试 'create' Controller 操作的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10548745/

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