我有一些 RSpec 控制器测试。有些有效,有些无效,我正试图弄清楚如何在地球上修复它们并提高它们的效率
理想情况下,我想看看是否可以将每个规范转换为以下形式
subject { ... }
it { ... }
it { ... }
it { ... }
请注意,对于我所有的控制器规格,我已经为实际的控制器操作编写了宏。这些宏都经过测试并且都可以工作,并且名称使它们的作用相当明显。
我的“创建”测试:
formats ||= ["html", "js"]
formats.each do |format|
context "valid attributes" do
subject { do_post_create( :customer, valid_attributes, format ) }
its(:response_code) { should eq(302)}
it { should redirect_to admin_customer_path(Customer.find_by_id(???))}
it { expect { subject }.to change(Customer, :count).by(1) }
end
context "invalid attributes" do
subject { do_post_create( :customer, invalid_attributes, format ) }
its(:response_code) { should eq(200)}
it { should render_template :new }
it { expect { subject }.to_not change(Customer, :count).by(1) }
end
end
在该规范中,我一直试图找出某种方法来从 post 语句中获取新创建对象的 ID。我试过“Customer.last”,但这似乎不起作用。有什么想法吗?
我的“更新”规范:
formats ||= ["html", "js"]
formats.each do |format|
context "valid attributes" do
let(:object) { FactoryGirl.create(:customer) }
subject { do_put_update( class_to_symbol(model), object.id, attributes, format ) }
its(:response_code) { should eq(302)}
it "does alter #{model}" do
do_put_update( class_to_symbol(model), object.id, attributes, format )
assigns(:customer).should eq(object)
flash[:notice].should =~ /Success/
object.reload
attributes.each do |key, value|
object.send(key.to_s).should eq(value)
end
end
end
context "invalid attributes" do
let(:object) { FactoryGirl.create("customer") }
let(:invalid_attributes) { {:username => "!"} }
subject { do_put_update( class_to_symbol(model), object.id, invalid_attributes, format ) }
its(:response_code) { should eq(200)}
it "does not alter #{model}" do
do_put_update( class_to_symbol(model), object.id, invalid_attributes, format )
assigns(:customer).should eq(object)
flash[:notice].should =~ /Fail/
object.reload
attributes.each do |key, value|
object.send(key.to_s).should_not eq(value)
end
end
end
end
在更新测试中,我想尝试以更简洁的方式表达第二个块,理想情况下,我可以对所有测试使用相同的“主题”语句。那可能吗?